import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:news_getx/config/storage.dart';
import 'package:news_getx/data/services/storage.dart';
import 'package:package_info_plus/package_info_plus.dart';

class ConfigService extends GetxService {
  static ConfigService get to => Get.find();

  bool isFirstOpen = false;
  PackageInfo? _platform;

  String get version => _platform?.version ?? "-";
  bool get isRelease => bool.fromEnvironment("dart.vm.product");
  Locale locale = Locale("en", "US");

  List<Locale> languages = [
    Locale('en', 'US'),
    Locale('zh', 'CN'),
  ];

  @override
  void onInit() {
    super.onInit();
    isFirstOpen = StorageService.to.getBool(StorageDeviceFirstOpenKey);
  }

  Future<void> getPlatform() async {
    _platform = await PackageInfo.fromPlatform();
  }

  // 标记用户已打开APP
  Future<bool> saveAlreadyOpen() {
    return StorageService.to.setBool(StorageDeviceFirstOpenKey, false);
  }

  void onInitLocale() {
    String langCode  = StorageService.to.getString(StorageLanguageCode);
    if (langCode .isEmpty) return;

    int index = languages.indexWhere((element) {
      return element.languageCode == langCode;
    });
    if (index < 0) return;
    locale = languages[index];
  }

  void onLocaleUpdate(Locale value) {
    locale = value;
    // 更新app的语言
    Get.updateLocale(value);
    StorageService.to.setString(StorageLanguageCode, value.languageCode);
  }
}