import 'package:auto_route/auto_route.dart';
import 'package:flutter/cupertino.dart';
import 'package:provider/provider.dart';
import 'package:telnow_mobile_new/main.dart';
import 'package:telnow_mobile_new/src/api/api_auth_provider.dart';
import 'package:telnow_mobile_new/src/api/jwt_token.dart';
import 'package:telnow_mobile_new/src/layouts/components/template.dart';
import 'package:telnow_mobile_new/src/storage/sharedpreferences/shared_preferences_manager.dart';
import 'package:telnow_mobile_new/src/utils/C.dart';
import 'package:telnow_mobile_new/src/utils/U.dart';
import 'package:telnow_mobile_new/src/utils/provider.dart';
import 'package:telnow_mobile_new/src/utils/ui_service.dart';

class AccountFunction{
  final ApiAuthProvider apiAuthProvider = ApiAuthProvider();
  final NotificationClass notification = NotificationClass();
  final JwtToken token = JwtToken();
  final SharedPreferencesManager _sharedPreferencesManager = SharedPreferencesManager();

  getUser(BuildContext context) async {
    final userModule = Provider.of<UserModule>(context, listen: false);
    var res = await token.getUserData();
    if (res != null) {
      var ver = await apiAuthProvider.getDataNoAuth('/api/license');
      userModule.setSerialNum(ver['serialNumber']);
      userModule.setList(res);
    } else {
      userModule.setResetData(true);
    }
  }

  switchLang(code, user) async {
    UIService.showLoading();
    var locale = 'id';
    if(code is int){
      var vl = U.retValidLang();
      locale = vl[code+1];
      code = code.toString();
    } else {
      locale = code;
    }
    try{
      Map<String, dynamic> p;
      p = {'userId': user['userId'], 'language': 'ID', '_language': code.toUpperCase()};
      var res = await apiAuthProvider.patchData('/api/informants/${user['id']}', p);
      if (res != null) {
        UIService.closeLoading();
        UIService.setLocale(Locale(locale));
        // context.setLocale(Locale(locale));
        notification.startNotification(code: code);
      } else {
        UIService.closeLoading();
      }
    }catch(e){
      UIService.closeLoading();
    }
  }

  Future<bool> setDndStatus(String id, bool dnd)async{
    var res = await apiAuthProvider.patchData('/api/informants/$id/setDnd', null, params: {'dnd': '${!dnd}'});
    if (res != null) {
      // Provider.of<UserModule>(context, listen: false).setDndStatus(dnd);
      return true;
    }
    return false;
  }
  
  logoutAction(BuildContext context)async{
    showLoading(context, text: '');
    String pid = U.getPidFromUrl(context.router.currentUrl);

    void loggingOut(){
      Navigator.of(context).pop();
      UIService.closeLoading();
      token.logout();
      context.navigateToPath("/app/$pid/login");
    }

    try {
      var tkn = _sharedPreferencesManager.getString(SharedPreferencesManager.keyFcmToken);

      if (tkn == null)
      {
        loggingOut();
      }
      else
      {
        var param = {'token': tkn, 'whiteListToken': false};
        var res = await apiAuthProvider.postData('/api/fcmTokens/remove/', null, param);

        if (res != null && res['success'])
        {
          loggingOut();
        }
        else
        {
          Future.delayed(const Duration(seconds: 5), () => UIService.closeLoading());
        }
      }
    } catch(e) {
      debugPrint(e.toString());
      UIService.navigateNamed("/app/$pid/login");
    }
  }
}