import 'package:flutter/material.dart';

import '../api/api_auth_provider.dart';
import '../utils/cache_manager.dart';

class HistoryRepository {
  final ApiAuthProvider _apiAuthProvider = ApiAuthProvider();

  //## cuma request doang, balikin hasil request ke cubit
  Future<List<dynamic>> getData(String key, String filter, int page, int size, List<dynamic> activeForum) async {
    try{
      String url = '/api/requestHistories/search/myReqHistory';
      var sort = ['datetimeRequest,desc'];

      var mission = await _apiAuthProvider.getData(url, {'size': size.toString(), 'page': page.toString(), 'sort': sort, 'filter': filter});
      List tempData = [];

      if (mission != null){
        if (mission.containsKey('_embedded')) {
          for (int i = 0; i < mission['_embedded']['requestHistories'].length; i++) {
            var isFrm = false;
            String id = "";
            String msg = "";

            activeForum.forEach((el) {
              if (el['ticketId'] == mission['_embedded']['requestHistories'][i]['ticketNo']) {
                id = el['id'];
                msg = el['desc'];
              }
            });

            if (id != "") isFrm = true;
            mission['_embedded']['requestHistories'][i]['_hasForum'] = isFrm;
            mission['_embedded']['requestHistories'][i]['_forumId'] = id;
            mission['_embedded']['requestHistories'][i]['_forumMsg'] = msg;

            tempData.add(mission['_embedded']['requestHistories'][i]);
          }
        }
      }

      // # cache manager
      CacheMan.writeData(key, tempData);

      return tempData;
    } catch(e){
      debugPrint(e.toString());
    }

    return [];
  }

  deleteData(List<String> params) async{
    var res = await _apiAuthProvider.postData("/api/requestHistories/deleteMyHistory", {"ticketNumbers": params}, null);

    if (res != null) {
      return res;
    }

    return null;
  }

  Future<List<dynamic>> getActiveForum(String url) async {
    try {
      var data = await _apiAuthProvider.getData(url, null);
      if (data != null) {
        // # caching disini
        CacheMan.writeData(url, data);

        return data;
      }
    } catch (e) {
      debugPrint(e.toString());
    }

    return [];
  }

  Future<Map<String, dynamic>> checkRequest(String filter) async {
    try {
      var res = await _apiAuthProvider.getData(
          '/api/requests/search/customFind', {'filter': filter});
      return res;
    } catch(e){
      debugPrint(e.toString());
    }
    return {};
  }
}