import 'package:dio/dio.dart';
import 'package:farm_tpf/custom_model/CropPlot.dart';
import 'package:farm_tpf/custom_model/Device.dart';
import 'package:farm_tpf/custom_model/EnvironmentParameter.dart';
import 'package:farm_tpf/custom_model/Harvest.dart';
import 'package:farm_tpf/custom_model/LocationUnit.dart';
import 'package:farm_tpf/custom_model/NotificationObjectDTO.dart';
import 'package:farm_tpf/custom_model/Supply.dart';
import 'package:farm_tpf/custom_model/UpdateNoti.dart';
import 'package:farm_tpf/custom_model/WaterType.dart';
import 'package:farm_tpf/custom_model/user.dart';
import 'package:farm_tpf/custom_model/user_request.dart';
import 'package:farm_tpf/data/api/dio_provider.dart';
import 'package:farm_tpf/data/api/rest_client.dart';
import 'package:farm_tpf/models/PagedResult.dart';
import 'package:farm_tpf/models/index.dart';
import 'package:farm_tpf/utils/const_common.dart';
import 'package:flutter/material.dart';

import '../../environment/app_config.dart';
import '../../presentation/screens/login/models/request_user.dart';
import '../../presentation/screens/login/models/response_user.dart';

class Repository {
  final dio = DioProvider.instance();

  Future<void> login(
    Function(ResponseUser) onSuccess,
    Function(String) onError, {
    required RequestUser requestUser,
  }) async {
    try {
      var url = FlavorConfig.values.baseUrl + '/api/authenticate';
      await dio.post(
        url,
        data: {
          'username': requestUser.username ?? '',
          'password': requestUser.password ?? '',
        },
      ).then(
        (value) {
          var res = ResponseUser.fromJson(value.data);
          onSuccess(res);
        },
      ).catchError((error) {
        var dioError = error as DioError;
        var message = dioError.response?.data['Error'];
        onError(message);
      });
    } catch (e) {
      onError('Đã có lỗi xảy ra');
    }
  }

  Future<List<ActionType>> getActionTypes() {
    final client = RestClient(dio);
    return client.getActionTypes();
  }

  Future<List<Harvest>> getHarvests() {
    final client = RestClient(dio);
    return client.getHarvests();
  }

  Future<List<WaterType>> getWaterTypes() {
    final client = RestClient(dio);
    return client.getWaterTypes();
  }

  Future<CropPlot> getPlotDetail(int cropId, {int page = 0, int size = 20}) {
    final client = RestClient(dio);
    return client.getCropDetail(cropId, page: page, size: size);
  }

  Future<CropPlot> getPlotDetailByCode(String cropCode, {int page = 0, int size = 20}) {
    final client = RestClient(dio);
    return client.getCropDetailByCode(cropCode, page: page, size: size);
  }

  Future<List<Crop>> getPlots({int page = 0, int size = 20, String searchString = ''}) {
    final client = RestClient(dio);
    return client.getPlots(page: page, size: size, query: searchString);
  }

  Future<void> updatePlot(TbCropDTO tbCropDTO) {
    final client = RestClient(dio);
    return client.updateCrop(tbCropDTO);
  }

  Future<User> signInWithCredentials(String username, String password) {
    final client = RestClient(dio);
    return client.login(UserRequest(username: username, password: password));
  }

  Future<PagedResult<T>> getInfinityList<T>(String url, {int page = 0, int size = 20}) async {
    var initUrl = "/api/activities/latest-env-by-activity-type/1/2";
    var url = ConstCommon.baseUrl + initUrl + "?page=$page&paged=true&size=$size";
    var response = await dio.get(url);

    final value = PagedResult<T>.fromJson(response.data, getInstanceClass());
    return value;
  }

  Future<List<Supply>> getSupplies(String type, {String query = ""}) async {
    final client = RestClient(dio);
    return client.getSupplies(
      type,
      query: query,
    );
  }

  Future<List<Device>> getDeviceForActivity() async {
    final client = RestClient(dio);
    return client.getDeviceForActivity();
  }

  Future<void> updateAllNotification(String status) {
    final client = RestClient(dio);
    return client.updateAllNotification(status);
  }

  Future<void> updateNoti(UpdateNoti updateNoti) {
    final client = RestClient(dio);
    return client.updateNoti(updateNoti);
  }

  Future<NotificationObjectDTO> getNotifications({int page = 0, int size = 20}) async {
    var url = ConstCommon.baseUrl + "/api/notifications-current-user?page=$page&size=$size&sort=sendDate,DESC";
    var response = await dio.get(url);

    final value = NotificationObjectDTO.fromJson(response.data);
    return value;
  }

  Future<List<LocationUnit>> getLocationUnits(
      {required LocationType locationType, required int filterId, int page = 0, int size = 500, String query = ''}) {
    final client = RestClient(dio);
    var response;
    switch (locationType) {
      case LocationType.province:
        response = client.getProvinces(filterId, page: page, size: size, query: query);
        break;
      case LocationType.district:
        response = client.getDistricts(filterId, page: page, size: size, query: query);
        break;
      case LocationType.ward:
        response = client.getWards(filterId, page: page, size: size, query: query);
        break;
      default:
        response = client.getCountries(query: query);
    }
    return response;
  }

  Object getInstanceClass() {
    var instanceClass;
    if (1 == 1) {
      instanceClass = Crop();
    }
    return instanceClass;
  }

  //Action
  Future<void> createAction(Function(dynamic) onSuccess, Function(dynamic) onError,
      {required String apiAddAction, required String paramActivity, required String activityAction, required List<String> filePaths}) async {
    var formData = FormData();
    filePaths.forEach((f) {
      formData.files.add(MapEntry("images", MultipartFile.fromFileSync(f)));
    });
    formData.fields.add(MapEntry(paramActivity, activityAction));
    try {
      await dio.post("${ConstCommon.baseUrl}/$apiAddAction", data: formData).then((value) {
        onSuccess(value.data);
      });
    } on DioError catch (e) {
      onError(e);
    }
  }

  Future<void> updateAction(Function(dynamic) onSuccess, Function(dynamic) onError,
      {required String apiUpdateAction, required String paramActivity, required String activityAction, required List<String> filePaths}) async {
    var formData = FormData();
    filePaths.forEach((f) {
      formData.files.add(MapEntry("images", MultipartFile.fromFileSync(f)));
    });
    formData.fields.add(MapEntry(paramActivity, activityAction));
    try {
      await dio.post("${ConstCommon.baseUrl}/$apiUpdateAction", data: formData).then((value) {
        onSuccess(value.data);
      });
    } on DioError catch (e) {
      onError(e);
    }
  }

  //Device
  Future<List<Device>> getDevices(String query) {
    final client = RestClient(dio);
    return client.getDevices(query: query);
  }

  //Environment Parameter
  Future<List<EnvironmentParameter>> getEnvironmentParameters({required int cropId, int page = 0, int size = 20}) {
    final client = RestClient(dio);
    return client.getEnvironmentParameters(cropId, page: page, size: size);
  }
}
