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

class HomeFunction{
  final SharedPreferencesManager sharedPreferencesManager = locator<SharedPreferencesManager>();
  final ApiAuthProvider apiAuthProvider = ApiAuthProvider();
  final JwtToken token = JwtToken();

  getProfileData(BuildContext context)async{
    if (!Provider.of<ServiceModule>(context, listen: false).initialized()) {
      Provider.of<ServiceModule>(context, listen: false).setInitialized(true);

      try{
        var license = await U.getLicense(showErr: false);
        Provider.of<UserModule>(context, listen: false).setHouseKeeping(license['houseKeepingFunction']);
      }catch(e){}

      try{
        var res = await token.getUserData(context);
        if(res != null){
          Provider.of<UserModule>(context, listen: false).setList(res);
          Provider.of<UserModule>(context, listen: false).setProfile(res['_profile']['data']);
          Provider.of<UserModule>(context, listen: false).setDndStatus(res['dnd']);

          getOptions(context);
        } else {
          Provider.of<ServiceModule>(context, listen: false).setInitialized(false);
          Provider.of<UserModule>(context, listen: false).setResetData(true);
        }
      }catch(e){
        showError(context, e.toString());
        Provider.of<ServiceModule>(context, listen: false).setInitialized(false);
        Provider.of<UserModule>(context, listen: false).setResetData(true);
      }
    }
  }

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

      var val = await CacheMan.readData(url);
      if (val != null) {
        Provider.of<ServiceModule>(context, listen: false).setScoope(val['data']);
      }

      var res = await apiAuthProvider.getData(url, null, context);
      if (res != null) {
        CacheMan.writeData(url, res);
        Provider.of<ServiceModule>(context, listen: false).setScoope(res);
      }

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

        var profile = Provider.of<UserModule>(context, listen: false).profile();
        if(profile['topMenu']['show'] != null && profile['topMenu']['show'] == true) {
          if(U.newServerVersion(1709864293)){
            getTopMenuNew(context);
          }
          else{
            getTopMenu(context);
            getReqGroup(context);
          }
        }
        if(profile['specialOffer'] != null && profile['specialOffer']['show'] == true) getSpecialOffer(context);
        if(profile['frequentlyRequested'] != null && profile['frequentlyRequested']['show'] == true) getFrequentlyRequested(context);
        if(profile['banner'] != null && profile['banner']['show'] == true) getBanner(context);
        if(profile['quickAction'] != null && profile['quickAction']['show'] == true) getQuickAction(context);
        getUnreadMessages(context);
      }
      Provider.of<ServiceModule>(context, listen: false).setInitialized(false);
    } catch (e) {
      Provider.of<ServiceModule>(context, listen: false).setInitialized(false);
      print(e.toString());
    }
  }

  getSpecialOffer(BuildContext context) async {
    try {
      String url = '/api/informants/search/request/specialOffer/'+Provider.of<ServiceModule>(context, listen: false).scoopeValue();

      var val = await CacheMan.readData(url);
      if (val != null) {
        Provider.of<ServiceModule>(context, listen: false).setSpecialOffer(val['data']);
      }

      var res = await apiAuthProvider.getData(url, null, context);
      if (res != null) {
        if (res.length > 0) {
          CacheMan.writeData(url, res);
          Provider.of<ServiceModule>(context, listen: false).setSpecialOffer(res);
        } else {
          Provider.of<ServiceModule>(context, listen: false).setSpecialOffer([]);
        }
      }
    } catch (e) {
      print(e.toString());
      Provider.of<ServiceModule>(context, listen: false).setSpecialOffer([]);
    }
  }

  getTopMenuNew(BuildContext context) async {
    try {
      var url = '/api/requestGroups/search/dashboard/topMenu/'+Provider.of<ServiceModule>(context, listen: false).scoopeValue();

      var val = await CacheMan.readData('$url?responseServantGroup=${U.servantDisplay()}');
      if (val != null) {
        Provider.of<ServiceModule>(context, listen: false).setTopMenu(val['data']['topMenu']);
        Provider.of<ServiceModule>(context, listen: false).setReqGroup(val['data']['excludeTopMenu']);
      }

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

  getTopMenu(BuildContext context) async {
    try {
      var url = '/api/requestGroups/search/topMenu/'+Provider.of<ServiceModule>(context, listen: false).scoopeValue();

      var val = await CacheMan.readData('$url?responseServantGroup=${U.servantDisplay()}');
      if (val != null) {
        Provider.of<ServiceModule>(context, listen: false).setTopMenu(val['data']);
      }

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

        if (tempData.length > 0) {
          CacheMan.writeData('$url?responseServantGroup=${U.servantDisplay()}', res);
          Provider.of<ServiceModule>(context, listen: false).setTopMenu(tempData);
        } else {
          CacheMan.writeData('$url?responseServantGroup=${U.servantDisplay()}', []);
          Provider.of<ServiceModule>(context, listen: false).setTopMenu([]);
        }
      }
      else{
        Provider.of<ServiceModule>(context, listen: false).setTopMenu([]);
      }
    } catch (e) {
      print(e.toString());
      Provider.of<ServiceModule>(context, listen: false).setTopMenu([]);
    }
  }

  getReqGroup(BuildContext context) async {
    try {
      var url = '/api/requestGroups/search/excludeTopMenu/'+Provider.of<ServiceModule>(context, listen: false).scoopeValue();

      var val = await CacheMan.readData('$url?responseServantGroup=${U.servantDisplay()}');
      if (val != null) {
        Provider.of<ServiceModule>(context, listen: false).setReqGroup(val['data']);
      }

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

        if (tempData.length > 0) {
          CacheMan.writeData('$url?responseServantGroup=${U.servantDisplay()}', res);
          Provider.of<ServiceModule>(context, listen: false).setReqGroup(tempData);
        } else {
          CacheMan.writeData('$url?responseServantGroup=${U.servantDisplay()}', []);
          Provider.of<ServiceModule>(context, listen: false).setReqGroup([]);
        }
      }
    } catch (e) {
      print(e.toString());
      Provider.of<ServiceModule>(context, listen: false).setReqGroup([]);
    }
  }

  getFrequentlyRequested(BuildContext context) async {
    try {
      var url = '/api/requestHistories/search/frequently/request/' + Provider.of<ServiceModule>(context, listen: false).scoopeValue();

      var val = await CacheMan.readData(url);
      if (val != null) {
        Provider.of<ServiceModule>(context, listen: false).setData(val['data']);
      }

      var res = await apiAuthProvider.getData(url, null, context);
      if (res != null) {
        if (res.length > 0) {
          CacheMan.writeData(url, res);
          Provider.of<ServiceModule>(context, listen: false).setData(res);
        } else {
          Provider.of<ServiceModule>(context, listen: false).setData([]);
        }
      }
    } catch (e) {
      print(e.toString());
      Provider.of<ServiceModule>(context, listen: false).setData([]);
    }
  }

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

      var val = await CacheMan.readData(url);
      if (val != null) {
        Provider.of<ServiceModule>(context, listen: false).setBanner(val['data']);
      }

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

  getQuickAction(BuildContext context) async {
    try {
      String url = '/api/informants/search/request/quickAction/'+Provider.of<ServiceModule>(context, listen: false).scoopeValue();

      var val = await CacheMan.readData(url);
      if (val != null) {
        Provider.of<ServiceModule>(context, listen: false).setQuickAct(val['data']);
      }

      var res = await apiAuthProvider.getData(url, null, context);
      if (res != null) {
        if (res.length > 0) {
          CacheMan.writeData(url, res);
          Provider.of<ServiceModule>(context, listen: false).setQuickAct(res);
        } else {
          Provider.of<ServiceModule>(context, listen: false).setQuickAct([]);
        }
      }
    } catch (e) {
      print(e.toString());
      Provider.of<ServiceModule>(context, listen: false).setQuickAct([]);
    }
  }

  getUnreadMessages(BuildContext context) async {
    try {
      var res = await apiAuthProvider.getData('/api/messages/search/myMessages', null, context);
      if (res != null) {
        List tempData = [];
        Provider.of<ServiceModule>(context, listen: false).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'] != Provider.of<UserModule>(context, listen: false).user()['userId']){
              Provider.of<ServiceModule>(context, listen: false).setUnreadMessage(true);
            }
            tempData.add(res['_embedded']['myMessages'][i]);
          }
        }

        Provider.of<ServiceModule>(context, listen: false).setMessage([]);
        if (tempData.length > 0) {
          Provider.of<ServiceModule>(context, listen: false).setMessage(tempData);
        }
      }
    } catch (e) {
      print(e.toString());
    }
  }

  onRefresh(BuildContext context){
    var profile = Provider.of<UserModule>(context, listen: false).profile();
    if(profile['topMenu']['show'] != null && profile['topMenu']['show'] == true) {
      if(U.newServerVersion(1709864293)){
        getTopMenuNew(context);
      }
      else{
        getTopMenu(context);
        getReqGroup(context);
      }
    }
    if(profile['specialOffer'] != null && profile['specialOffer']['show'] == true) getSpecialOffer(context);
    if(profile['frequentlyRequested'] != null && profile['frequentlyRequested']['show'] == true) getFrequentlyRequested(context);
    if(profile['banner'] != null && profile['banner']['show'] == true) getBanner(context);
    if(profile['quickAction'] != null && profile['quickAction']['show'] == true) getQuickAction(context);
    getUnreadMessages(context);
  }
}