
import { ConnectorService } from '../connector/connector.service'
import { AuthenticationService } from '../authentication/authentication.service'
import { CredentialWifiRequest } from './models/credential-wifi.request'
import { CredentialWifiResponse } from './models/credential-wifi.response'
import { Injectable } from '@angular/core';
import { Platform } from '@ionic/angular';
import { Observable } from 'rxjs';
import { CommonService } from '../common/common.service';
import { AuthenticatedUser } from '../authentication/models/authenticated-user'
import { AlertControllerService } from 'src/app/hmg-common/ui/alert/alert-controller.service';
import { TranslatorService } from 'src/app/hmg-common/services/translator/translator.service';


declare var WifiWizard2: any;

@Injectable({
    providedIn: 'root'
})



export class AutoConnectService {
    passWord: any;
    userName: any;
    public buttons: any[]

    public static credentialInfoWifi = 'Services/Patients.svc/REST/Hmg_SMS_Get_By_ProjectID_And_PatientID';

    constructor(
        public con: ConnectorService,
        public authService: AuthenticationService,
        public cs: CommonService,
        public platform: Platform,
        public ts: TranslatorService
    ) { }



    public getCredentialWifiService(patientID: any, projectID: any, onError: any): Observable<CredentialWifiResponse> {
        //const request = this.authService.getAuthenticatedRequest();
        const request = new CredentialWifiRequest();
        request.PatientID = patientID;
        request.ProjectID = projectID;
        //   request.SetupID= '91877';
        return this.con.post(AutoConnectService.credentialInfoWifi, request, onError);
    }


    /*
    call service to get Password and Name
    call plugin to connected
    if connected then open url
    */
    public getCredentialWifi(buttons) {
        this.buttons = buttons;

        const authUser = this.authService.getAuthenticatedUser();
        this.getCredentialWifiService(authUser.PatientID, authUser.ProjectID, () => { }).subscribe((result: any) => {

            if (this.cs.validResponse(result)) {

                if (this.cs.hasData(result.Hmg_SMS_Get_By_ProjectID_And_PatientIDList)) {
                    //get the password and userNmae
                    // send it to url  
                    this.passWord = result.Hmg_SMS_Get_By_ProjectID_And_PatientIDList[0].Password;
                    this.userName = result.Hmg_SMS_Get_By_ProjectID_And_PatientIDList[0].UserName;
                    this.scanWifi();
                }
            }
        });
    }

    public async scanWifi() {

        //  this.platform.ready().then(() => {  
        if (this.platform.is("ios")) {
            //check avaliable ssid 
            this.checkConnected();
        } //end if iOS
        else if (this.platform.is("android")) {

            // alert("Android");
            try {
                let result = await WifiWizard2.scan()
                let resultList = result;
                for (let i = 0; i < resultList.length; i++) {
                    let ssid = resultList[i].SSID;
                    if (ssid == "CS-Guest") {
                        // alert("ssid " + ssid);
                        i = resultList.length; // to stop the loop
                    } // if ssid == cs-guest
                } // for loop

                this.checkConnected();
            } catch (e) {
                //alert( 'Error to  Scan: '+ e );
                // this.alertService.presentConfirm(
                //     this.ts.trPK('general', 'info'),
                //     this.ts.trPK('error', 'scan-wifi'),
                //     this.ts.trPK('general', 'ok'), () => {
                //         this.alertService.dismiss();
                //     }
                // );

                this.cs.presentAcceptDialog(this.ts.trPK('error', 'scan-wifi'), () => { })


            }

            //
        } //end if Android
        //});
    }

    public async checkConnected() {

        try {
            let result = await WifiWizard2.getConnectedSSID()
            if (result == "CS-Guest") {
                // alert('WIFI SSID '+ result);
                this.disconnectNetwork();
            } else {
                this.startConnected();
            }
        } catch (e) {
            alert('Error to  display WIFI SSID: ' + e);
            // conneted to local HMG 
            this.startConnected();
        }

    }

    public async startConnected() {
        alert(" startConnected ");

        try {
            let result;
            if (this.platform.is("ios")) {
                result = await WifiWizard2.iOSConnectNetwork("CS-Guest")
            } else if (this.platform.is("android")) {

                result = await WifiWizard2.connect("CS-Guest", false, false)
            }
            alert('conected: ' + result);
            this.buttons[5][5].title = 'home,auto-connected-wifi';

            //let url="http://192.168.104.251/guest/HMG-Guest.php?_browser=1&cmd=login&essid=CS-Guest&apname=CS_AP_9&apgroup=CloudSolutons%20AP%20Group&url=http%3A%2F%2Fwww%2Emsftconnecttest%2Ecom%252Fredirect&Name=6200&Pass=7809";

            let url = "http://192.168.104.251/guest/HMG-Guest.php?_browser=1&cmd=login&essid=CS-Guest&apname=CS_AP_9&apgroup=CloudSolutons%20AP%20Group&url=http%3A%2F%2Fwww%2Emsftconnecttest%2Ecom%252Fredirect&Name=" + this.userName + "&Pass=" + this.passWord + "";

            setTimeout(() => {
                this.cs.openBrowser(url);
            }, 2 * 1000);

        } catch (e) {
            //display error for check the avaliable Wifi
            // alert( 'Error to  connected: '+ e );
            // this.alertService.presentConfirm(
            //     this.ts.trPK('general', 'info'),
            //     this.ts.trPK('error', 'connect-Wifi'),
            //     this.ts.trPK('general', 'ok'), () => {
            //     this.alertService.dismiss();
            //     }
            // );

            this.cs.presentAcceptDialog(this.ts.trPK('error', 'connect-Wifi'), () => { });

        }

    }



    public async disconnectNetwork() {

        try {
            let result;
            if (this.platform.is("ios")) {
                result = await WifiWizard2.iOSDisconnectNetwork("CS-Guest")
            } else if (this.platform.is("android")) {

                result = await WifiWizard2.disconnect("CS-Guest")
            }
            this.buttons[5][5].title = 'home,auto-wifi';
            alert('Succssful Disconected ' + result);
        } catch (e) {
            //display error for check the avaliable Wifi
            // alert( 'Error to  connected: '+ e );
            // this.alertService.presentConfirm(
            //     this.ts.trPK('general', 'info'),
            //     this.ts.trPK('error', 'disconnect-Wifi'),
            //     this.ts.trPK('general', 'ok'), () => {
            //     this.alertService.dismiss();
            //     }
            // );

            this.cs.presentAcceptDialog(this.ts.trPK('error', 'disconnect-Wifi'), () => { })

        }

    }

}