// ignore_for_file: unnecessary_question_mark, non_constant_identifier_names, unused_local_variable, prefer_interpolation_to_compose_strings, use_build_context_synchronously

import 'dart:io';
import 'dart:convert';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:general_package/get_device_info/get_device_info.dart';
import 'package:general_package/mainUrl_provider/mainUrl_provider.dart';
import 'package:geolocator/geolocator.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
// import 'package:toast/toast.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/foundation.dart';
import 'dart:developer' as logDev;
import 'package:intl/intl.dart';

import '../authservices/auth_service.dart';

class APIService {
  BuildContext context;
  APIService(this.context);
  Future<bool> GetConnect() async {
    var connectivityResult = await (Connectivity().checkConnectivity());
    bool isInternetOn = false;
    if (connectivityResult == ConnectivityResult.none) {
      isInternetOn = false;
    } else if (connectivityResult == ConnectivityResult.mobile) {
      isInternetOn = true;
    } else if (connectivityResult == ConnectivityResult.wifi) {
      isInternetOn = true;
    }
    return isInternetOn;
  }

  getMainURL() {
    String mainURL =
        Provider.of<mainURLChangeNotifier>(context, listen: false).mainURL;
    return mainURL;
  }

  Future<Position?> determinePosition() async {
    bool serviceEnabled;
    LocationPermission permission;

    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        // Permissions are denied, next time you could try
        // requesting permissions again (this is also where
        // Android's shouldShowRequestPermissionRationale
        // returned true. According to Android guidelines
        // your App should show an explanatory UI now.
        Future.error('Location permissions are denied');
      }
    }
    if (permission == LocationPermission.deniedForever) {
      // Permissions are denied forever, handle appropriately.
      Future.error(
          'Location permissions are permanently denied, we cannot request permissions.');
    }

    // Test if location services are enabled.
    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      // Location services are not enabled don't continue
      // accessing the position and request users of the
      // App to enable the location services.
      // return Future.error('Location services are disabled.');
      Position? position = await Geolocator.getLastKnownPosition();
      if (position != null) {
        return position;
      }
      Future.error('Location services are disabled.');
    }
    // When we reach here, permissions are granted and we can
    // continue accessing the position of the device.
    return await Geolocator.getCurrentPosition();
  }

  Future<dynamic?> getData(String? url) async {
    try {
      Future<bool> internetActive = GetConnect();

      if (await internetActive) {
        print("API Service Started");
        String mainURL =
            Provider.of<mainURLChangeNotifier>(context, listen: false).mainURL;
        var dURL = mainURL + url!;
        print(dURL);
        print("Get Device Info Started");
        var deviceInfo = await DeviceInfo()
            .getDeviceInfo(Get.currentRoute, Get.previousRoute);
        print("Get Device Info Ended");
        var header = <String, String>{
          'Content-Type': 'application/json; charset=UTF-8',
          'Accept': 'application/json',
        };
        header.addAll(deviceInfo);

        if (authService.token.isNotEmpty) {
          header.addAll({"Authorization": "Bearer ${authService.token}"});
        }
        print(header);

        final response = await http.get(Uri.parse(dURL), headers: header);
        if (kDebugMode) {
          print(response.body);
          // logDev.log(response.body);
        }
        if (response.statusCode == 200 || response.statusCode == 201) {
          dynamic res = json.decode(response.body);

          if (res["message"] != null) {
            if (res["message"].toString().isNotEmpty) {
              Fluttertoast.showToast(
                  msg: res["message"],
                  toastLength: Toast.LENGTH_LONG,
                  gravity: ToastGravity.BOTTOM,
                  timeInSecForIosWeb: 1,
                  backgroundColor: Colors.green,
                  webPosition: "center",
                  webBgColor: "#008000",
                  textColor: Colors.white,
                  fontSize: 16.0);
            }
          }
          return res;
        } else {
          dynamic res = json.decode(response.body);

          if (response.statusCode == 401) {
            authService.logout("/homeScreenView");
          }
          if (res["message"] != null) {
            FToast().init(context);
            FToast().showToast(child: const Text("data"));
            Fluttertoast.showToast(
                msg: res["message"].toString(),
                toastLength: Toast.LENGTH_LONG,
                gravity: ToastGravity.BOTTOM,
                timeInSecForIosWeb: 1,
                backgroundColor: Colors.red,
                textColor: Colors.white,
                webPosition: "center",
                webBgColor: "#FF0000",
                fontSize: 16.0);
          }
        }
        print("API Service Ended");
      }
    } on SocketException catch (_) {
      Fluttertoast.showToast(
          msg: "Please check your internet",
          toastLength: Toast.LENGTH_LONG,
          gravity: ToastGravity.BOTTOM,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.red,
          textColor: Colors.white,
          webPosition: "center",
          webBgColor: "#FF0000",
          fontSize: 16.0);
    }
    return null;
  }

  Future<dynamic?> postData(
    String? url,
    Map<String, dynamic> data,
  ) async {
    try {
      bool internetActive = await GetConnect();
      if (internetActive) {
        print("API Service Started");
        String mainURL =
            Provider.of<mainURLChangeNotifier>(context, listen: false).mainURL;
        var dURL = mainURL + url!;
        print(dURL);
        print("Get Device Info Started");
        var deviceInfo = await DeviceInfo()
            .getDeviceInfo(Get.currentRoute, Get.previousRoute);
        print("Get Device Info Ended");
        var header = <String, String>{
          'Content-Type': 'application/json; charset=UTF-8',
          'Accept': 'application/json',
        };
        header.addAll(deviceInfo);

        if (authService.token.isNotEmpty) {
          header.addAll({"Authorization": "Bearer ${authService.token}"});
        }
        print(header);
        data.forEach((key, value) {
          if (value.runtimeType == DateTime) {
            // data[key]=value.toIso8601String();
            data[key] = DateFormat('dd-MM-yyyy hh:mm:ss a').format(value);
          }
        });
        var body = json.encode(data);
        if (kDebugMode) {
          print(dURL);
          print(body);
        }
        final response =
            await http.post(Uri.parse(dURL), headers: header, body: body);
        if (kDebugMode) {
          print(response.body);
          // logDev.log(response.body);
        }
        if (response.body != null ||
            response.body.isNotEmpty ||
            response.body != " ") {
          if (response.statusCode == 200 || response.statusCode == 201) {
            dynamic res = json.decode(response.body);
            if (res["message"] != null) {
              if (res["message"].toString().isNotEmpty) {
                Fluttertoast.showToast(
                    msg: res["message"],
                    toastLength: Toast.LENGTH_LONG,
                    gravity: ToastGravity.BOTTOM,
                    timeInSecForIosWeb: 1,
                    backgroundColor: Colors.green,
                    textColor: Colors.white,
                    webPosition: "center",
                    webBgColor: "#008000",
                    fontSize: 16.0);
              }
            }
            return res;
          } else {
            if (response.statusCode == 401) {
              authService.logout("/homeScreenView");
            }
            dynamic res = json.decode(response.body);
            if (res["message"] != null) {
              Fluttertoast.showToast(
                  msg: res["message"].toString(),
                  toastLength: Toast.LENGTH_LONG,
                  gravity: ToastGravity.BOTTOM,
                  timeInSecForIosWeb: 1,
                  backgroundColor: Colors.red,
                  textColor: Colors.white,
                  webPosition: "center",
                  webBgColor: "#FF0000",
                  fontSize: 16.0);
            }
          }
        }
        print("API Service Ended");
      }
    } on SocketException catch (_) {
      Fluttertoast.showToast(
          msg: "Please check your internet",
          toastLength: Toast.LENGTH_LONG,
          gravity: ToastGravity.BOTTOM,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.red,
          textColor: Colors.white,
          webPosition: "center",
          webBgColor: "#FF0000",
          fontSize: 16.0);
    }
  }
}
