import 'dart:developer';
import 'dart:io';

import 'package:diplomaticquarterapp/config/config.dart';
import 'package:diplomaticquarterapp/core/service/client/base_app_client.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/locator.dart';
import 'package:diplomaticquarterapp/uitl/PlatformBridge.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/uitl/utils.dart';
import 'package:diplomaticquarterapp/widgets/dialogs/alert_dialog.dart';
import 'package:diplomaticquarterapp/widgets/dialogs/confirm_dialog.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:wifi/wifi.dart';

import 'gif_loader_dialog_utils.dart';

class HMGNetworkConnectivity {
  final _platformBridge = PlatformBridge.shared();
  final BuildContext context;
  Function callBack;

  final String GUEST_SSID = "HMG-MobileApp";
  final String PATIENT_SSID = "GUEST-POC";

  HMGNetworkConnectivity(this.context);

  start(){
    checkAndConnectIfNoInternet();
  }

  void checkAndConnectIfNoInternet() async {
    // getMyWifiCredentials((username, password){
    //   print("");
    // });
    //
    // return;

    String pingUrl = "$BASE_URL$PING_SERVICE";
    // pingUrl = "https://captive.apple.com";

    String ssid = await Wifi.ssid.catchError((error) {
      log(error.toString());
    });

    bool alreadyConnected = ssid == GUEST_SSID;

    BaseAppClient().simpleGet(pingUrl, onSuccess: (dynamic response, int statusCode) {
      log("Having internet with status code: $statusCode");
    }, onFailure: (String error, int statusCode) {
      if (alreadyConnected)
        showFailDailog(TranslationBase.of(context).failedToAccessHmgServices);
      else {
        confirmFromUser(connectForLocalAccess);
      }
    });
  }

  void confirmFromUser(VoidCallback confirmCallback) {
    TranslationBase translator = TranslationBase.of(context);

    void doIt() {
      ConfirmDialog(
          context: context,
          confirmMessage: translator.wantToConnectWithHmgNetwork,
          okText: translator.yes,
          okFunction: () {
            // ConfirmDialog.closeAlertDialog(context);
            confirmCallback();
          },
          cancelText: translator.no,
          cancelFunction: () {
            ConfirmDialog.closeAlertDialog(context);
          }).showAlertDialog(context);
    }

    if (Platform.isAndroid)
      Wifi.list(GUEST_SSID).then((value) {
        if (!value.indexWhere((element) => element.ssid == GUEST_SSID).isNegative) doIt();
      });
    else
      doIt();
  }

  void showFailDailog(String message) {
    TranslationBase translator = TranslationBase.of(context);
    AlertDialogBox(
        context: context,
        okText: translator.ok,
        confirmMessage: message,
        okFunction: () {
          AlertDialogBox.closeAlertDialog(context);
        }).showAlertDialog(context);
  }


  connectForLocalAccess(){
    GifLoaderDialogUtils.showMyDialog(context);
    _platformBridge.connectHMGGuestWifi(GUEST_SSID).then((value) async{
      if(value == 0){
        GifLoaderDialogUtils.hideDialog(context);
      }else{
        getPatientWifiCredentials((username, password) async{
          final result = await _platformBridge.connectHMGInternetWifi(PATIENT_SSID, username, password).catchError((err) => print(err.toString()));
          GifLoaderDialogUtils.hideDialog(context);
          if(result == 1){
            // Success
          }
        });
      }
    });
  }

  getPatientWifiCredentials(Function(String username, String password) successCallback){
    final body = <String, dynamic>{"PatientID" : "1231755"};
    locator<BaseAppClient>().post(WIFI_CREDENTIALS, body:body, onSuccess: (dynamic response, int statusCode){
      print(response);
      var data = response["Hmg_SMS_Get_By_ProjectID_And_PatientIDList"];
      if(data is List && data.first != null){
        final username = data.first['UserName'];
        final password = data.first['Password'];
        if(username != null && password != null && username.isNotEmpty && password.isNotEmpty){
          successCallback(username, password);
        }
      }
    }, onFailure: (String error, int statusCode){
      print(error);
    }, bypassConnectionCheck: true);
  }
  // void next() {
  //   if (Platform.isIOS) {
  //     confirmFromUser_iOS();
  //   } else if (Platform.isAndroid) {
  //     confirmFromUser();
  //   }
  // }

  // void confirmFromUser_iOS() {
  //   String message = "You don't have internet access, Do you want to connect with HMG Network to use App.\n\nMake sure you are in HMG Network range";
  //   ConfirmDialog(
  //       context: context,
  //       confirmMessage: message,
  //       okText: "Yes",
  //       okFunction: () {
  //         ConfirmDialog.closeAlertDialog(context);
  //         callBack();
  //       },
  //       cancelText: "No",
  //       cancelFunction: () {
  //         ConfirmDialog.closeAlertDialog(context);
  //       }).showAlertDialog(context);
  // }

  // void connect_Android() {
  //   // enable the Wifi if its off
  //   PlatformBridge()
  //       .enableWifiIfNot()
  //       .then((value) => {
  //             if (value == true)
  //               {
  //                 callBack()
  //                 // Wifi.list(SSID)
  //                 //     .then((value1) => {
  //                 //           if (value1.length > 0) {callBack()} else {log("No HMG network in range")}
  //                 //         })
  //                 //     .catchError((e) {
  //                 //   log(e);
  //                 // })
  //               }
  //           })
  //       .catchError((error) {
  //     showFailDailog(error);
  //   });
  // }
}
