import 'package:flutter/cupertino.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/injector/injector.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:provider/provider.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/cache_manager.dart';
import 'package:telnow_mobile_new/src/utils/provider.dart';
import 'package:telnow_mobile_new/src/utils/ui_service.dart';

class HomeFunction{
  final SharedPreferencesManager sharedPreferencesManager = locator<SharedPreferencesManager>();
  final ApiAuthProvider apiAuthProvider = ApiAuthProvider();
  final JwtToken token = JwtToken();
  final BuildContext context = UIService.context!;
  late final ServiceModule serviceModule = Provider.of<ServiceModule>(context, listen: false);
  late final UserModule userModule = Provider.of<UserModule>(context, listen: false);

  getProfileData(BuildContext context)async{
    if (!serviceModule.initialized()) {
      serviceModule.setInitialized(true);

      try{
        var license = await U.getLicense(showErr: false);
        userModule.setHouseKeeping(license['houseKeepingFunction']);
      }catch(e){
        debugPrint(e.toString());
      }

      try{
        var res = await token.getUserData();
        if(res != null){
          userModule.setList(res);
          userModule.setProfile(res['_profile']['data']);
          userModule.setDndStatus(res['dnd']);

          getOptions(context);
        } else {
          serviceModule.setInitialized(false);
          userModule.setResetData(true);
        }
      }catch(e){
        showError(context, e.toString());
        serviceModule.setInitialized(false);
        userModule.setResetData(true);
      }
    }
  }

  getOptions(BuildContext context) async {
    try {
      String url = '/api/systemSettings/search/scope/system/label';

      var val = await CacheMan.readData(url);
      if (val != null) {
        serviceModule.setScoope(val['data']);
      }

      var res = await apiAuthProvider.getData(url, null);
      if (res != null) {
        CacheMan.writeData(url, res);
        serviceModule.setScoope(res);
      }

      if(serviceModule.scoope().isNotEmpty){
        //dev-note: cek 1-1, mekanisme load nya. ada yg bikin berat tidak?
        for (int i = 0; i < serviceModule.scoope().length; i++) {
          if (sharedPreferencesManager.isKeyExists(SharedPreferencesManager.keyScoope)! && sharedPreferencesManager.getString(SharedPreferencesManager.keyScoope) == serviceModule.scoope()[i]['key']) {
            serviceModule.setScoopeValue(serviceModule.scoope()[i]['key']);
            serviceModule.setScoopeName(serviceModule.scoope()[i]['value']);
          }
        }

        var profile = userModule.profile();
        if(profile['topMenu']['show'] != null && profile['topMenu']['show'] == true) {
          getTopMenuNew();
        }
        if(profile['specialOffer'] != null && profile['specialOffer']['show'] == true) getSpecialOffer(context);
        if(profile['frequentlyRequested'] != null && profile['frequentlyRequested']['show'] == true) getFrequentlyRequested();
        if(profile['banner'] != null && profile['banner']['show'] == true) getBanner(context);
        if(profile['quickAction'] != null && profile['quickAction']['show'] == true) getQuickAction(context);
        getUnreadMessages(context);
      }
      serviceModule.setInitialized(false);
    } catch (e) {
      serviceModule.setInitialized(false);
      print(e.toString());
    }
  }

  getSpecialOffer(BuildContext context) async {
    try {
      String url = '/api/informants/search/request/specialOffer/'+serviceModule.scoopeValue();

      var val = await CacheMan.readData(url);
      if (val != null) {
        serviceModule.setSpecialOffer(val['data']);
      }

      var res = await apiAuthProvider.getData(url, null);
      if (res != null) {
        if (res.length > 0) {
          CacheMan.writeData(url, res);
          serviceModule.setSpecialOffer(res);
        } else {
          serviceModule.setSpecialOffer([]);
        }
      }
    } catch (e) {
      print(e.toString());
      serviceModule.setSpecialOffer([]);
    }
  }

  getTopMenuNew() async {
    try {
      var url = '/api/requestGroups/search/dashboard/topMenu/'+serviceModule.scoopeValue();

      var val = await CacheMan.readData('$url?responseServantGroup=${U.servantDisplay()}');
      if (val != null) {
        serviceModule.setTopMenu(val['data']['topMenu']);
        serviceModule.setReqGroup(val['data']['excludeTopMenu']);
      }

      var res = await apiAuthProvider.getData(url, {'responseServantGroup': U.servantDisplay().toString()});
      if (res != null) {
        CacheMan.writeData('$url?responseServantGroup=${U.servantDisplay()}', res);
        serviceModule.setTopMenu(res['topMenu']);
        serviceModule.setReqGroup(res['excludeTopMenu']);
      }
    } catch (e) {
      print(e.toString());
      serviceModule.setTopMenu([]);
      serviceModule.setReqGroup([]);
    }
  }

  getTopMenu() async {
    try {
      var url = '/api/requestGroups/search/topMenu/'+serviceModule.scoopeValue();

      var val = await CacheMan.readData('$url?responseServantGroup=${U.servantDisplay()}');
      if (val != null) {
        serviceModule.setTopMenu(val['data']);
      }

      var res = await apiAuthProvider.getData(url, {'responseServantGroup': U.servantDisplay().toString()});
      if (res != null) {
        List tempData = [];
        tempData.addAll(res);

        if (tempData.length > 0) {
          CacheMan.writeData('$url?responseServantGroup=${U.servantDisplay()}', res);
          serviceModule.setTopMenu(tempData);
        } else {
          CacheMan.writeData('$url?responseServantGroup=${U.servantDisplay()}', []);
          serviceModule.setTopMenu([]);
        }
      }
      else{
        serviceModule.setTopMenu([]);
      }
    } catch (e) {
      print(e.toString());
      serviceModule.setTopMenu([]);
    }
  }

  getReqGroup() async {
    try {
      var url = '/api/requestGroups/search/excludeTopMenu/'+serviceModule.scoopeValue();

      var val = await CacheMan.readData('$url?responseServantGroup=${U.servantDisplay()}');
      if (val != null) {
        serviceModule.setReqGroup(val['data']);
      }

      var res = await apiAuthProvider.getData(url, {'responseServantGroup': U.servantDisplay().toString()});
      if (res != null) {
        List tempData = [];
        tempData.addAll(res);

        if (tempData.length > 0) {
          CacheMan.writeData('$url?responseServantGroup=${U.servantDisplay()}', res);
          serviceModule.setReqGroup(tempData);
        } else {
          CacheMan.writeData('$url?responseServantGroup=${U.servantDisplay()}', []);
          serviceModule.setReqGroup([]);
        }
      }
    } catch (e) {
      print(e.toString());
      serviceModule.setReqGroup([]);
    }
  }

  getFrequentlyRequested() async {
    try {
      var url = '/api/requestHistories/search/frequently/request/' + serviceModule.scoopeValue();

      var val = await CacheMan.readData(url);
      if (val != null) {
        serviceModule.setData(val['data']);
      }

      var res = await apiAuthProvider.getData(url, null);
      if (res != null) {
        if (res.length > 0) {
          CacheMan.writeData(url, res);
          serviceModule.setData(res);
        } else {
          serviceModule.setData([]);
        }
      }
    } catch (e) {
      debugPrint(e.toString());
      serviceModule.setData([]);
    }
  }

  getBanner(BuildContext context) async {
    try {
      var url = '/api/informants/search/banner';

      var val = await CacheMan.readData(url);
      if (val != null) {
        serviceModule.setBanner(val['data']);
      }

      var res = await apiAuthProvider.getData(url, {'size': '20'});
      if (res != null) {
        if (res.length > 0) {
          CacheMan.writeData(url, res);
          serviceModule.setBanner(res);
        } else {
          serviceModule.setBanner([]);
        }
      }
    } catch (e) {
      print(e.toString());
      serviceModule.setBanner([]);
    }
  }

  getQuickAction(BuildContext context) async {
    try {
      String url = '/api/informants/search/request/quickAction/'+serviceModule.scoopeValue();

      var val = await CacheMan.readData(url);
      if (val != null) {
        serviceModule.setQuickAct(val['data']);
      }

      var res = await apiAuthProvider.getData(url, null);
      if (res != null) {
        if (res.length > 0) {
          CacheMan.writeData(url, res);
          serviceModule.setQuickAct(res);
        } else {
          serviceModule.setQuickAct([]);
        }
      }
    } catch (e) {
      print(e.toString());
      serviceModule.setQuickAct([]);
    }
  }

  getContactCenter(BuildContext context) async {
    try{
      var url = "/api/contactCenter/whatsapp" ;
      var res = await apiAuthProvider.getData(url, null);
      if (res != null) {
        serviceModule.setContactCenter(res);
      }
    }catch(e){
      serviceModule.setContactCenter('');
    }
  }

  getUnreadMessages(BuildContext context) async {
    try {
      var res = await apiAuthProvider.getData('/api/messages/search/myMessages', null);
      if (res != null) {
        List tempData = [];
        serviceModule.setUnreadMessage(false);
        if(res.containsKey('_embedded')){
          for (int i = 0; i < res['_embedded']['myMessages'].length; i++) {
            if(res['_embedded']['myMessages'][i]['lastReadStatus'] == 'UNREAD' && res['_embedded']['myMessages'][i]['userId'] != userModule.user()['userId']){
              serviceModule.setUnreadMessage(true);
            }
            tempData.add(res['_embedded']['myMessages'][i]);
          }
        }

        serviceModule.setMessage([]);
        if (tempData.isNotEmpty) {
          serviceModule.setMessage(tempData);
        }
      }
    } catch (e) {
      print(e.toString());
    }

    try{
      String url = '/api/messages/search/myForum';
      var res = await apiAuthProvider.getData(url, null);
      if (res != null) {
        for (int i = 0; i < res.length; i++) {
          if (res[i]['readStatus'] == 'UNREAD' && res[i]['userId'] != userModule.user()['userId']){
            serviceModule.setUnreadMessage(true);
          }
        }
      }
    }catch(e){}
  }

  onRefresh(BuildContext context){
    var profile = userModule.profile();
    if(profile['topMenu']['show'] != null && profile['topMenu']['show'] == true) {
      getTopMenuNew();
    }
    if(profile['specialOffer'] != null && profile['specialOffer']['show'] == true) getSpecialOffer(context);
    if(profile['frequentlyRequested'] != null && profile['frequentlyRequested']['show'] == true) getFrequentlyRequested();
    if(profile['banner'] != null && profile['banner']['show'] == true) getBanner(context);
    if(profile['quickAction'] != null && profile['quickAction']['show'] == true) getQuickAction(context);
    getUnreadMessages(context);
  }
}