import 'dart:convert';

import 'package:unit2/model/profile/work_history.dart';
import 'package:http/http.dart' as http;
import 'package:unit2/model/utils/agency_position.dart';
import 'package:unit2/model/utils/position.dart';
import 'package:unit2/utils/request.dart';

import '../../utils/urls.dart';

class WorkHistoryService {
  static final WorkHistoryService _instance = WorkHistoryService();
  static WorkHistoryService get instance => _instance;

////get all workhistories
  Future<List<WorkHistory>> getWorkExperiences(
      int profileId, String token) async {
    List<WorkHistory> workExperiences = [];
    String authToken = "Token $token";
    Map<String, String> headers = {
      'Content-Type': 'application/json; charset=UTF-8',
      'Authorization': authToken
    };
    String path = Url.instance.workhistory() + profileId.toString();
    try {
      http.Response response = await Request.instance
          .getRequest(path: path, headers: headers, param: {});
      if (response.statusCode == 200) {
        Map data = jsonDecode(response.body);
        if (data['data'] != null) {
          data['data'].forEach((var workHistory) {
            workExperiences.add(WorkHistory.fromJson(workHistory));
          });
        }
      }
    } catch (e) {
      throw e.toString();
    }
    return workExperiences;
  }


////delete workhistory
  Future<bool> delete(
      {required int profileId,
      required String token,
      required WorkHistory work}) async {
    bool? success;
    Map<String, dynamic> params = {"force_mode": "true"};
    String authToken = "Token $token";
    String path = "${Url.instance.workhistory()}$profileId/";
    Map body = {
      "id": work.id,
      "position_id": work.position!.id,
      "agency_id": work.agency!.id,
      "from_date": work.fromDate?.toString(),
      "to_date": work.toDate?.toString(),
      "monthly_salary": work.monthlySalary,
      "appointment_status": work.appointmentStatus,
      "salary_step": work.sgStep,
      "salary_grade": work.salaryGrade,
    };
    Map<String, String> headers = {
      'Content-Type': 'application/json; charset=UTF-8',
      'Authorization': authToken
    };
    try {
      http.Response response = await Request.instance.deleteRequest(
          path: path, headers: headers, body: body, param: params);

      if(response.statusCode == 200){
        Map data = jsonDecode(response.body);
        success = data['success'];
      }else{
        success = false;
      }
    } catch (e) {
      throw e.toString();
    }
    return success!;
  }


  ////edit work history
  Future<Map<dynamic,dynamic>> update({required WorkHistory oldWorkHistory, required WorkHistory newWorkHistory, required String token, required String profileId})async{
    Map<dynamic, dynamic>? statusResponse={};
    String authtoken = "Token $token";
    String path = '${Url.instance.workhistory()}$profileId/';
     Map<String, String> headers = {
      'Content-Type': 'application/json; charset=UTF-8',
      'Authorization': authtoken
    };
    Map body = {
      "id":newWorkHistory.id,
      "position_id":newWorkHistory.position!.id,
      "agency_id":newWorkHistory.agency!.id,
      "from_date":newWorkHistory.fromDate?.toString(),
      "to_date":newWorkHistory.toDate?.toString(),
      "monthly_salary":newWorkHistory.monthlySalary,
      "appointment_status":newWorkHistory.appointmentStatus,
      "salary_grade":newWorkHistory.salaryGrade,
      "sg_step":newWorkHistory.sgStep,
      "_positionName":newWorkHistory.position!.title!,
      "_agencyName":newWorkHistory.agency!.name!,
      "_agencyCatId":newWorkHistory.agency!.category!.id!,
      "_privateEntity":newWorkHistory.agency!.privateEntity,
      "oldPosId":oldWorkHistory.position!.id,
      "_oldAgencyId":oldWorkHistory.agency!.id,
      "oldFromDate":oldWorkHistory.fromDate?.toString(),
    };  
    try{
      http.Response response = await Request.instance.putRequest(path: path, headers: headers, body: body, param: {});
      if(response.statusCode == 200 ){
        Map data = jsonDecode(response.body);
        statusResponse = data;
      }else{
        statusResponse.addAll({'success':false});
      }
      return statusResponse;
    }catch(e){
      throw e.toString();
    }
  }

  ////Add work history
  Future<Map<dynamic, dynamic>>add({required WorkHistory workHistory, required String token, required int profileId , required bool isPrivate})async{
        String authtoken = "Token $token";
    String path = '${Url.instance.workhistory()}$profileId/';
      Map<String, String> headers = {
      'Content-Type': 'application/json; charset=UTF-8',
      'Authorization': authtoken
    };
    Map<dynamic,dynamic> statusResponse = {};
        Map body = {
      'position_id':workHistory.position?.id,
      'agency_id': workHistory.agency?.id,
      'from_date': workHistory.fromDate?.toString(),
      'to_date': workHistory.toDate?.toString(),
    'monthly_salary': workHistory.monthlySalary,
      'appointment_status': workHistory.appointmentStatus,
      'salary_grade': workHistory.salaryGrade,
      'sg_step':workHistory.sgStep,
      '_positionName':workHistory.position?.title,
      '_agencyName':workHistory.agency?.name,
      '_agencyCatId':workHistory.agency?.category?.id,
      '_privateEntity':workHistory.agency?.privateEntity,
    };
    try{
      http.Response response = await Request.instance.postRequest(path: path,param: {},body: body,headers: headers);
      if(response.statusCode == 201){
        Map data = jsonDecode(response.body);
        statusResponse = data;
      
      }else{
        statusResponse.addAll({'success':false});
      }
      return statusResponse;
    }catch(e){
      throw e.toString();
    }

  }

////get agency position
  Future<List<Position>> getAgencyPosition() async {
    List<Position> agencyPositions = [];
    String path = Url.instance.getPositions();
    Map<String, String> headers = {
      'Content-Type': 'application/json; charset=UTF-8',
    };
    try {
      http.Response response = await Request.instance
          .getRequest(param: {}, path: path, headers: headers);
      if (response.statusCode == 200) {
        Map data = jsonDecode(response.body);
        if (data['data'] != null) {
          data['data'].forEach((var agencyPosition) {
            Position position = Position.fromJson(agencyPosition);
            agencyPositions.add(position);
          });
        }
      }
    } catch (e) {
      throw (e.toString());
    }
    return agencyPositions;
  }

//get appointment status
  List<AppoinemtStatus> getAppointmentStatusList() {
    return [
      AppoinemtStatus(value: "Appointed", label: "Appointed"),
      AppoinemtStatus(value: "Casual", label: "Casual"),
      AppoinemtStatus(
          value: "Contact of Service", label: "Contract of Service"),
      AppoinemtStatus(value: "Coterminous", label: "Coterminous"),
      AppoinemtStatus(value: "Elected", label: "Elected"),
      AppoinemtStatus(value: "Job Order", label: "Job Order"),
         AppoinemtStatus(value: "Permanent", label: "Permanent"),
      AppoinemtStatus(value: "Elected", label: "Elected"),
    ];
  }
}
