import 'dart:io';

import 'package:dio/dio.dart';
import 'package:road24_mobile/data/http/ApiException.dart';
import 'package:road24_mobile/data/http/ApiResponse.dart';
import 'package:road24_mobile/data/http/CustomDioInterceptor.dart';
import 'package:road24_mobile/data/repository/UserRepository.dart';
import 'package:road24_mobile/data/response/AuthResponse.dart';
import 'package:road24_mobile/model/utils/Config.dart';
import 'package:road24_mobile/my_app.dart';

class DeviceRepository {
  String _getLanguage(String language) {
    if (language == 'uz') return 'oz';
    if (language == 'oz') return 'uz';
    return language;
  }

  Dio preparing() {
    final baseDioOptions = new BaseOptions(
      baseUrl: 'https://api.road24.uz/api/',
      headers: {
        'Api-Version': '1.0',
        'Accept': 'application/json',
        'App-OS': Platform.operatingSystem,
        'Accept-Language': _getLanguage(Config.language),
      },
      connectTimeout: 60000,
      receiveTimeout: 60000,
      sendTimeout: 60000,
      contentType: 'application/json',
      responseType: ResponseType.json,
    );
    Dio dio = new Dio(baseDioOptions);
    dio.interceptors.add(CustomDioInterceptor(
      responseBody: true,
      requestBody: true,
      requestHeader: true,
    ));
    return dio;
  }

  Future<dynamic> registerDevice(
      {required DeviceType deviceType,
      required String registrationId,
      required bool active,
      required String deviceId}) async {
    try {
      final response = await preparing().post(
        'devices/',
        data: {
          "registration_id": registrationId,
          "device_id": deviceId,
          "active": active,
          "type": (deviceType == DeviceType.ANDROID)
              ? "android"
              : (deviceType == DeviceType.IOS)
                  ? "ios"
                  : "",
          "language": Config.language,
        },
      );
      if (response.statusCode == 200 ||
          response.statusCode == 202 ||
          response.statusCode == 201 ||
          response.statusCode == 204) {
        ApiResponse apiResponse = ApiResponse.fromJson(response.data);
        print(apiResponse);
        if (apiResponse.isSuccess()) return apiResponse;
      }
    } catch (error) {
      if (error is DioError) {
        if (error.response?.statusCode == 403 ||
            error.response?.statusCode == 401) {
          // if (error.requestOptions.path ==
          //     '/api/mobile/v1/users/auth/token/refresh/') {
          //   MyApp.navigatorKey.currentState!.pushAndRemoveUntil(
          //       FadeRoute(page: PhonePage()), (route) => false);
          //   setTokens(null, null);

          //   return null;
          // }

          var value = await UserRepository()
              .tokenRefresh(refresh: MyApp.preferences!.getRefreshToken()!);

          MyApp.preferences?.setToken(
            AuthResponse.fromJson(value).access,
          );
          MyApp.preferences
              ?.setRefreshToken(AuthResponse.fromJson(value).refresh);

          await preparing().post(
            'devices/',
            data: {
              "registration_id": registrationId,
              "device_id": deviceId,
              "active": active,
              "type": (deviceType == DeviceType.ANDROID)
                  ? "android"
                  : (deviceType == DeviceType.IOS)
                      ? "ios"
                      : "",
            },
          ).then((value) {
            ApiResponse apiResponse = ApiResponse.fromJson(value.data);
            return apiResponse;
          });
        }
      }
    }
  }

  Future<dynamic> deactivateDevice({required String registeredId}) async {
    try {
      final response = await preparing().delete(
        'devices/$registeredId/',
      );
      print(response.data);
      if (response.statusCode == 204) {
        ApiResponse apiResponse = ApiResponse.fromJson(response.data);
        print(apiResponse);
        if (apiResponse.isSuccess()) return apiResponse;
      }
    } catch (error) {
      if (error is DioError) {
        if (error.response?.statusCode == 403 ||
            error.response?.statusCode == 401) {
          // if (error.requestOptions.uri.path ==
          //     '/api/mobile/v1/users/auth/token/refresh/') {
          //   MyApp.navigatorKey.currentState!.pushAndRemoveUntil(
          //       FadeRoute(page: PhonePage()), (route) => false);
          //   setTokens(null, null);

          //   return null;
          // }
          await UserRepository()
              .tokenRefresh(refresh: MyApp.preferences!.getRefreshToken()!)
              .then((value) {
            MyApp.preferences?.setToken(
              AuthResponse.fromJson(value).access,
            );
            MyApp.preferences
                ?.setRefreshToken(AuthResponse.fromJson(value).refresh);
          });
          await preparing()
              .delete(
            'devices/$registeredId/',
          )
              .then((value) {
            ApiResponse apiResponse = ApiResponse.fromJson(value.data);
            return apiResponse;
          });
        }
        if (error.response?.statusCode == 409)
          throw ApiException(
            errMessage: error.response?.data["message"] ?? error.message,
            dioError: error,
            responseStatus: error.response?.statusCode,
          );
        throw ApiException(
          errMessage: error.toString(),
          dioError: error,
          responseStatus: error.response?.statusCode,
        );
      }
      throw error;
    }
  }

  Future<dynamic> changeLanguageTo(String language) async {
    String registrationId = MyApp.preferences?.getMessagingToken() ?? "";
    // MyApp.sharedPreferences.getString(Config.userMessagingToken);
    final response = await preparing().put('devices/$registrationId/', data: {
      'registration_id': MyApp.preferences?.getMessagingToken(),
      "type": (Platform.isAndroid)
          ? "android"
          :
          // (Platform.isIOS)
          "ios",
      // 'registration_id': MyApp.sharedPreferences.get(Config.userMessagingToken),
      'language': language,
    });
    return response.data;
  }
}

setTokens(String? token, String? userRefreshToken) {
  MyApp.preferences?.setToken(token);
  MyApp.preferences?.setRefreshToken(userRefreshToken);
}

enum DeviceType { ANDROID, IOS }
