// ignore_for_file: unnecessary_overrides
import 'dart:async';
import 'dart:io';

import 'package:http/http.dart' as http;
import 'package:logger/logger.dart';

import 'package:IQ/main.dart';

class APIService {
  static Future getUrl(url) async {
    try {
      http.Request response;
// ignore: unrelated_type_equality_checks
      response = http.Request('GET', Uri.parse(url));
      http.StreamedResponse request = await response.send();
      if (request.statusCode != 200) {
        return request.statusCode;
      }
      String res = await request.stream.bytesToString();
      return res;
    } catch (e) {
      if (e is SocketException) {
        return 0;
      } else if (e is TimeoutException) {
        return -2;
      }
    }
  }

  static Future get(route, [bool auth = true]) async {
    try {
      var baseUrl = storage.read('baseUrl');
      var token = storage.read('token');
      // isExpired = JwtDecoder.isExpired(token!);
      // if (isExpired) {
      //   storage.remove('token');
      //   Get.offAllNamed(Routes.AUTOLOGIN);
      //   return -1;
      // }
      http.Request response;
      response = http.Request('GET', Uri.parse('$baseUrl/$route'));
      if (auth) response.headers.addAll({'Authorization': 'Bearer $token'});

      http.StreamedResponse request = await response.send();
      Logger().e("token $token");
      if (request.statusCode != 200) {
        token = null;
        storage.remove('token');
        // Get.offAllNamed(Routes.SELECT_I_S_P);
        return request.statusCode;
      }
      String res = await request.stream.bytesToString();
      Logger().e("request $res");
      return res;
    } catch (e) {
      if (e is SocketException) {
        return 0;
      } else if (e is TimeoutException) {
        return -2;
      }
    }
  }

  static Future post(route, String payload, [bool auth = true]) async {
    try {
      var baseUrl = storage.read('baseUrl');
      var token = storage.read('token');
      var request = http.Request(
        'POST',
        Uri.parse('$baseUrl/$route'),
      );
      request.bodyFields = {'payload': payload};
      // isExpired = JwtDecoder.isExpired(token!);
      // if (isExpired) {
      //   storage.remove('token');
      //   Get.offAllNamed(Routes.AUTOLOGIN);
      //   return -1;
      // }

      if (auth) {
        request.headers.addAll({
          'Authorization': 'Bearer $token',
          'Accept': 'application/json',
        });
      }

      http.StreamedResponse response = await request.send();
      if (response.statusCode != 200) {
        return response.statusCode;
      }
      String res = await response.stream.bytesToString();

      return res;
    } catch (e) {
      if (e is SocketException) {
        return 0;
      } else if (e is TimeoutException) {
        return -2;
      }
    }
  }
}
