import 'dart:convert';
import 'package:get/get.dart';
import 'package:http/http.dart' as http;
import 'package:device_info/device_info.dart';
import 'dart:io';

import 'default_response_api.dart';

class FuncoesGerais {
  //static const String urlLexLiteApi = "https://apis.lexstation.com/api/v1/";
  static const String tokenPadrao = "88IF8S1DLX8GFHL1WQW07VAXZE8XAT";
  static const String urlBaseNewCore = "https://newcore.services/newcore/";
  static const int appMobileCodigo = 18;
  static const String nomeApp = "modelo";
  static const int versaoAtual = 100;
  static const int usuCodPadrao = 1035;
  static const String youtubeApiKey =
      "AIzaSyAmqjP0MxgASbt98Px1_hqaIvcsqeHO15k"; //"AIzaSyA8jo3qsr-JJRm40iSHfkrzaMZXdMjo9v4";
  static const String channelId = "UCJ_EUoswNTvRGotJ-ROxaKw";
  static const String homeURL = "https://hightechx.com/";
  static const String dominioPermitido = "https://modelopublicidade.com.br/";
  static const String urlPDF = "https://app-cards.com/files/card-hightechx.pdf";

  static Future<bool> checkInternetConnection() async {
    bool retorno = true;
    try {
      final result = await InternetAddress.lookup('google.com')
          .timeout(Duration(seconds: 5));
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        retorno = true;
      } else {
        retorno = false;
      }
    } on SocketException catch (_) {
      retorno = false;
    } catch (err) {
      retorno = false;
    }

    return retorno;
  }

  static Future<String> getUsuToken() async {
    return Future<String>.value(tokenPadrao);
  }

  static Future<void> registraDevice(String? token) async {
    if (await FuncoesGerais.checkInternetConnection()) {
      if (token != null && token.isNotEmpty) {
        String url = FuncoesGerais.urlBaseNewCore +
            "api/v1/user/${FuncoesGerais.tokenPadrao}/registra_device";
        Map<String, String> heads = Map();
        heads["Content-type"] = "application/json; charset=utf-8";
        heads["auth-key"] = token;
        DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
        String model = "";
        int platformCoddigo = 0;
        if (Platform.isAndroid) {
          platformCoddigo = 2;
          var info = await deviceInfo.androidInfo;
          model = info.model;
        } else if (Platform.isIOS) {
          platformCoddigo = 1;
          var info = await deviceInfo.iosInfo;
          model = info.utsname.machine;
        }

        var objPost = new RegistraDeviceRequest(
          aPPMOBILECODIGO: appMobileCodigo,
          dEVICETOKEN: token,
          mODELODEVICE: model,
          pLATAFORMAMOBILECODIGO: platformCoddigo,
          uSUCOD: FuncoesGerais.usuCodPadrao,
        );

        try {
          var body = json.encode(objPost);
          //var response = await http.post(url, body: body,headers: heads);
          await http.post(Uri.parse(url), body: body, headers: heads);
          //var r = await http.post(url, body: body,headers: heads);
          //print(r);
          // if (response != null) {
          //   if (response.statusCode == 200) {
          //     var data = jsonDecode(response.body);
          //     retorno = LoginResponse.fromJson(data);
          //   }
          // }
        } catch (e) {}
      }
    }
    // else{
    //   print('Nada');
    // }
  }

  static Future<VersaoMinimaResponse> checkVersaoMinimaOk() async {
    VersaoMinimaResponse objRetorno = VersaoMinimaResponse(
        errorCode: 0,
        errorMessage: '',
        linkLoja: '',
        nome: '',
        versaoMinima: 0,
        vOk: true);
    if (await FuncoesGerais.checkInternetConnection()) {
      String url = FuncoesGerais.urlBaseNewCore +
          "api/v1/appmobile/${FuncoesGerais.tokenPadrao}/versaominima/$appMobileCodigo";
      Map<String, String> heads = Map();
      heads["Content-type"] = "application/json; charset=utf-8";

      try {
        http.Response response = await http.get(Uri.parse(url), headers: heads);
        if (!GetUtils.isNullOrBlank(response.body)!) {
          if (response.statusCode == 200) {
            var data = jsonDecode(response.body);
            objRetorno = VersaoMinimaResponse.fromJson(data);
            // PackageInfo packageInfo = await PackageInfo.fromPlatform();
            // var v = packageInfo.version.split('.');
            // int versaoAtual = 0;
            //if(v.length > 0)versaoAtual = v[0] != null && v[0].isNotEmpty ? int.parse(v[0]) : 0;
            if (objRetorno.versaoMinima! > FuncoesGerais.versaoAtual) {
              objRetorno.vOk = false;
            }
          } else {
            objRetorno.errorCode = 4;
            objRetorno.errorMessage =
                'Falha na comunição com a API error:${response.statusCode}.';
          }
        } else {
          objRetorno.errorCode = 3;
          objRetorno.errorMessage = 'Falha na comunição com o server.';
        }
      } catch (e) {
        objRetorno.errorCode = 2;
        objRetorno.errorMessage = 'Falha na comunição com o server.';
      }
    } else {
      objRetorno.errorCode = 1;
      objRetorno.errorMessage = 'Sem Conexão com a internet.';
    }

    return objRetorno;
  }
}
