import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../../common/models/index.dart';
import '../../../../common/routers/index.dart';
import '../../../../common/services/index.dart';
import '../../../../common/utils/index.dart';
import '../../../../common/widgets/index.dart';
import 'index.dart';

class SettingsCommonController extends GetxController {
  SettingsCommonController();

  final state = SettingsCommonState();
 

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    loadCacheSize();
    state.languageName = LanguageListExt.getCurrentLanguage().getDisplayName();
    super.onReady();
  }
 
  void openLogs() {
    Get.toNamed(O2OARoutes.homeSettingsLogs);
  }

  /// 
  /// 清除缓存
  /// 
  void clickClearCache() {
    O2UI.showConfirm(Get.context, 'settings_clear_cache_clear_confirm_msg'.trArgs([(state.cacheSize)]) , okPressed: () {
      _clearCache();
    });
  }

  void _clearCache() async {
    await O2FilePathUtil.clearCache();
    await O2FlutterMethodChannelUtils().clearCacheNative();
    Loading.toast('settings_clear_cache_clear_success'.tr);
    loadCacheSize();
  }

  ///
  /// 获取缓存目录大小
  /// 
  Future<void> loadCacheSize() async {
    int size = await O2FilePathUtil.cacheSizeTotal();
    if (size > 1024 * 1024 * 1024) { // G
      final s = (size / (1024 * 1024 * 1024));
      state.cacheSize = "${s.toStringAsFixed(2)} G";
    } else if (size > 1024 * 1024 ) { // M
      final s = (size / (1024 * 1024));
      state.cacheSize = "${s.toStringAsFixed(2)} M";
    } else if (size > 1024) {
      final s = (size / 1024);
      state.cacheSize = "${s.toStringAsFixed(2)} K";
    } else {
      state.cacheSize = "$size";
    }
  }
 
  // 切换语言
  changeLanguage() {
    final context = Get.context;
    if (context == null) {
      return ;
    }
     O2UI.showBottomSheetWithCancel(context, LanguageList.values.map((e) => ListTile(
      title: Text(e.getDisplayName()),
      onTap: () {
         Navigator.pop(context);
         updateLanguage(e);
      },
     )).toList());
  }
  updateLanguage(LanguageList lan) async {
    Get.updateLocale(lan.getLocale());
    SharedPreferenceService.to.putString(SharedPreferenceService.languageSaveKey, lan.getKey());
    state.languageName = lan.getDisplayName();
  }
}
