import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.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/mobile/message_broadcast.dart';
import 'package:telnow_mobile_new/src/layouts/mobile/message_select.dart';
import 'package:telnow_mobile_new/src/layouts/components/template.dart';
import 'package:telnow_mobile_new/src/layouts/web/message_broadcast.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';

class MessageFunction{
  final ApiAuthProvider apiAuthProvider = ApiAuthProvider();
  final JwtToken token = JwtToken();

  getUser(BuildContext context)async{
    var res = await token.getUserData();
    if(res != null){
      Provider.of<MessageModule>(context, listen: false).setUser(res);
      getDataMessages(context);
    }
  }

  getDataMessages(BuildContext context) async {
    getDataForum(context);
    String url = '/api/messages/search/myMessages';
    var val = await CacheMan.readData(url);
    if (val != null) {
      Provider.of<MessageModule>(context, listen: false).setData(val['data']);
    }

    var res = await apiAuthProvider.getData(url, null);
    if (res != null) {
      List tempData = [];
      if (res['_embedded'] != null) {
        for (int i = 0; i < res['_embedded']['myMessages'].length; i++) {
          tempData.add(res['_embedded']['myMessages'][i]);
        }
      }

      CacheMan.writeData(url, tempData);
      Provider.of<MessageModule>(context, listen: false).setData(tempData);
      Provider.of<MessageModule>(context, listen: false).setFirstLoad(true);
    } else {
      Provider.of<MessageModule>(context, listen: false).setFirstLoad(true);
    }
  }

  getDataForum(BuildContext context) async{
    String url = '/api/messages/search/myForum';
    var val = await CacheMan.readData(url);
    final messageModule = Provider.of<MessageModule>(context,listen: false);
    if (val != null){
      messageModule.setForum(val['data']);
    }

    var res = await apiAuthProvider.getData(url, null);
    if (res != null) {
      List tempData = [];
      for (int i = 0; i < res.length; i++) {
        tempData.add(res[i]);
      }

      CacheMan.writeData(url, tempData);
      messageModule.setForum(tempData);
      messageModule.setFirstLoad(true);
    } else {
      messageModule.setFirstLoad(true);
    }
  }

  setAsRead(context, ticketNo) async {
    var res = await apiAuthProvider.postData('/api/notifications/readMyForum/$ticketNo', null, null);
    if (res != null) {
    }
  }

  createMessage(BuildContext context) async{
    String url = '/api/tenants/search/customFind';
    List dataTenant = [];

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

    try{
      var res = await apiAuthProvider.getData(url, {'isPaged': 'true', 'size': '1000', 'sort': 'description'});
      if (res != null) {
        List tempData = [];
        if (res['_embedded'] != null) {
          for (int i = 0; i < res['_embedded']['tenants'].length; i++) {
            tempData.add(res['_embedded']['tenants'][i]);
          }
          if (tempData.length != 0) {
            CacheMan.writeData(url, tempData);
          }
          if(dataTenant.isEmpty){
            dataTenant.addAll(tempData);
          }
        }
      }
    } catch(e){
      print(e.toString());
    }

    if(U.webView(context)){
      navigateTo(context, WebMessageBroadcastPage(Provider.of<MessageModule>(context, listen: false).user(), dataTenant));
    }
    else{
      navigateTo(context, dataTenant.isEmpty ? MobMessageBroadcastPage(Provider.of<MessageModule>(context, listen: false).user(), []) : MobMessageSelectPage(Provider.of<MessageModule>(context, listen: false).user(), dataTenant));
    }
    onRefresh(context);
  }

  timeSet(time) {
    final now = DateTime.now();
    var localDateTime = DateTime.parse(time);

    if (localDateTime.day == now.day && localDateTime.month == now.month && localDateTime.year == now.year) {
      return DateFormat('Hm').format(localDateTime);
    }
    DateTime yesterday = now.subtract(Duration(days: 1));
    if (localDateTime.day == yesterday.day && localDateTime.month == yesterday.month && localDateTime.year == yesterday.year) {
      return 'yesterday'.tr();
    }
    return DateFormat('yMd').format(localDateTime);
  }

  onRefresh(BuildContext context) {
    try {
      getDataMessages(context);
    } catch (e) {
      print(e.toString());
    }
  }
}