import 'package:didvan/models/settings_data.dart';
import 'package:didvan/services/media/media.dart';
import 'package:didvan/services/storage/storage.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';

class AppInitializer {
  static Future<void> setupServices() async {
    if (!kIsWeb) {
      StorageService.appDocsDir =
          (await getApplicationDocumentsDirectory()).path;
      StorageService.appTempsDir = (await getTemporaryDirectory()).path;
      await _initializeFirebase();
      MediaService.init();
    }
  }

  static Future<SettingsData> initilizeSettings() async {
    final brightness = await StorageService.getValue(key: 'brightness');
    if (brightness != null) {
      final themeMode = brightness == 'dark' ? ThemeMode.dark : ThemeMode.light;
      final fontFamily = await StorageService.getValue(key: 'fontFamily');
      final fontScale = double.parse(
        await StorageService.getValue(key: 'fontSizeScale'),
      );
      return SettingsData(
        fontFamily: fontFamily,
        fontScale: fontScale,
        themeMode: themeMode,
      );
    } else {
      await StorageService.setValue(
        key: 'notificationTimeRangeStart',
        value: '00:00',
      );
      await StorageService.setValue(
        key: 'notificationTimeRangeEnd',
        value: '23:59',
      );
      await StorageService.setValue(
        key: 'fontFamily',
        value: 'Dana-FA',
      );
      await StorageService.setValue(
        key: 'fontSizeScale',
        value: '1',
      );
      await StorageService.setValue(
        key: 'brightness',
        value: 'light',
      );
      return SettingsData(
        fontFamily: 'Dana-FA',
        fontScale: 1,
        themeMode: ThemeMode.light,
      );
    }
  }

  static Future<void> _initializeFirebase() async {
    try {
      await Firebase.initializeApp(
        options: const FirebaseOptions(
          apiKey: 'AIzaSyBp-UHjWeM0H0UHtX5yguFKG-riMzvvCzw',
          appId: '1:935017686266:android:f9cbc9aba8e3d65ed2d543',
          messagingSenderId: '935017686266',
          projectId: 'didvan-9b7da',
        ),
      );
    } catch (e) {
      Firebase.app();
    }
    final FirebaseMessaging fcm = FirebaseMessaging.instance;
    await fcm.requestPermission(
      alert: true,
      announcement: false,
      badge: true,
      carPlay: false,
      criticalAlert: false,
      provisional: false,
      sound: true,
    );
  }
}
