import { Injectable } from '@angular/core';
import { NavController, ToastController, LoadingController, AlertController, Platform } from '@ionic/angular';
import { Router } from '@angular/router';
import { TranslatorService } from '../translator/translator.service';
import { AlertControllerService } from '../../ui/alert/alert-controller.service';
import { Response } from '../models/response';
import { Location } from '@angular/common';
import { ThemeableBrowser } from '@ionic-native/themeable-browser/ngx';
import { BrowserConfig } from './models/browser-config';
import { LaunchNavigator, LaunchNavigatorOptions } from '@ionic-native/launch-navigator/ngx';
import { Device } from '@ionic-native/device/ngx';


@Injectable({
    providedIn: 'root'
})
export class CommonService {
    private progressLoaders: any[] = [];
    private loadingProgress: any;
    constructor(
        public nav: NavController,
        public router: Router,
        public location: Location,
        public ts: TranslatorService,
        public loadingController: LoadingController,
        public toastController: ToastController,
        public alertController: AlertControllerService,
        public alertControllerIonic: AlertController,
        public themeableBrowser: ThemeableBrowser,
        public launchNavigation: LaunchNavigator,
        public platform: Platform,
        public device: Device

    ) { }

    public back() {
        // this.location.back();
        this.nav.goBack();
    }

    public round(value: number, decimal: number): string {
        const valueStr = value.toString();
        const dotIndex = valueStr.indexOf('.');

        if (dotIndex >= 0) {
            return valueStr.toString().substr(0, dotIndex + decimal);
        } else {
            return value.toString();
        }

    }

    public toastPK(page: string, key: string) {
        this.toast(this.ts.trPK(page, key));
    }
    async  toast(message: string) {
        const toast = await this.toastController.create({
            message: message,
            showCloseButton: true,
            position: 'middle',
            duration: 2000,
            closeButtonText: this.ts.trPK('general', 'done')
        });
        toast.present();
    }

    async startLoading() {
        this.stopLoading();
        const loader = await this.loadingController.create({
            spinner: 'bubbles',
            duration: 30000,
            message: this.ts.trPK('error', 'wait'),
            translucent: true
        });

        this.progressLoaders.push(loader);
        return await loader.present();
    }


    public mobileNumber(number: string) {
        return number.substr(1, number.length - 1);
    }
    public testFunction() {

    }

    public stopLoading() {

        /*
          loading progress must be implemented
          as synchronous
        */
        setTimeout(() => {
            for (const loader of this.progressLoaders) {
                loader.dismiss();
            }
            this.progressLoaders = [];

        }, 1000);
    }

    public presentAlert(message: string) {
        this.alertDialog(null, this.ts.trPK('general', 'ok'), this.ts.trPK('general', 'alert'), message);

    }


    public presentConfirmDialog(message: string, onAccept: any, onCancel: any) {

        this.confirmAlertDialog(onAccept, this.ts.trPK('general', 'ok'),
            null, this.ts.trPK('general', 'cancel'),
            this.ts.trPK('general', 'confirm'), message);
    }

    async presentConfirmDialogOld(message: string, onAccept: any, onCancel: any) {

        this.alertController.presentConfirm(
            this.ts.trPK('general', 'confirm'),
            message,
            this.ts.trPK('general', 'ok'),
            () => {
                this.alertController.dismiss();
                onAccept();
            },
            () => {
                this.alertController.dismiss();
                onCancel();
            }
        );
    }


    public presentAcceptDialog(message: string, onAccept: any) {

        this.alertDialog(onAccept, this.ts.trPK('general', 'ok'), this.ts.trPK('general', 'confirm'), message);

    }

    async presentAcceptDialogOld(message: string, onAccept: any) {
        this.alertController.presentConfirm(
            this.ts.trPK('general', 'confirm'),
            message,
            this.ts.trPK('general', 'ok'),
            () => {
                this.alertController.dismiss();
                onAccept();
            }
        );
    }

    public confirmBackDialogOld(message: string) {
        this.alertController.presentConfirm(
            this.ts.trPK('general', 'info'),
            message,
            this.ts.trPK('general', 'ok'),
            () => {
                this.back();
                this.alertController.dismiss();
            }
        );
    }

    public confirmBackDialog(message: string) {

        this.alertDialog(
            () => {
                this.back();
            },
            this.ts.trPK('general', 'ok'), this.ts.trPK('general', 'info'), message);

    }


    public showErrorMessageDialogOld(onClick: any, okLabel: string, message: string) {
        this.alertController.presentConfirm(
            this.ts.trPK('general', 'alert'),
            message, okLabel, () => {
                if (onClick) {
                    onClick();
                }
                this.alertController.dismiss();
            }
        );



    }

    public showErrorMessageDialog(onClick: any, okLabel: string, message: string) {
        this.alertDialog(onClick, okLabel, this.ts.trPK('general', 'alert'), message);

    }


    public showConnectionErrorDialogOld(onClick: any, okLabel: string) {

        this.alertController.presentConfirm(
            this.ts.trPK('general', 'alert'),
            this.ts.trPK('error', 'conn'),
            okLabel, () => {
                if (onClick) {
                    onClick();
                }
                this.alertController.dismiss();

            }
        );

    }


    public showConnectionErrorDialog(onClick: any, okLabel: string) {
        this.alertDialog(onClick, okLabel, this.ts.trPK('general', 'alert'), this.ts.trPK('error', 'conn'));

    }

    async confirmAlertDialog(onAccept: any, acceptLabel: string, onCancel: any, cancelLabel: string, title: string, message: string) {
        this.clearAllAlerts();
        const alert = await this.alertControllerIonic.create({
            header: this.ts.trPK('general', 'confirm'),
            message: message,
            buttons: [
                {
                    text: cancelLabel,
                    role: 'cancel',
                    handler: () => {
                        if (onCancel) {
                            onCancel();
                        }
                        this.alertControllerIonic.dismiss();
                    }
                }, {
                    text: acceptLabel,
                    handler: () => {
                        if (onAccept) {
                            onAccept();
                        }
                        this.alertControllerIonic.dismiss();
                    }
                }
            ]
        });
       // this.alerts.push(alert);
        await alert.present();
    }

    async alertDialog(onAccept: any, acceptLabel: string, title: string, message: string) {
        this.clearAllAlerts();
        const alert = await this.alertControllerIonic.create({
            header: title,
            message: message,
            buttons: [
                {
                    text: acceptLabel,
                    handler: () => {
                        if (onAccept) {
                            onAccept();
                        }
                        this.alertControllerIonic.dismiss();
                    }
                }
            ]
        });
       // this.alerts.push(alert);
        await alert.present();
    }

    private alerts: any[] = [];
    public clearAllAlerts() {
        /*
        for (const alert of this.alerts) {
            this.alertControllerIonic.dismiss(alert);
        }

        */
        this.alerts = [];
    }



    public getDeviceInfo(): string {

        if (this.platform.is('mobile')) {
            const os = this.platform.is('ios') ? 'Iphone' : 'android';
            return os + ' - ' + this.device.platform + ' - ' + this.device.version + ' , ' + this.device.manufacturer;
        } else {
            return navigator.userAgent;
        }

    }

    public getDeviceType(): string {
        if (this.platform.is('mobile')) {
            return 'Mobile ' + (this.platform.is('ios') ? 'Iphone' : 'android');
        } else {
            return 'Desktop';
        }

    }
    public validResponse(result: Response): boolean {
        if (result.MessageStatus === 1) {
            return true;
        } else if (result.MessageStatus === 2) {
            return this.hasData(result['SameClinicApptList']);
        }
        return false;
    }

    public openBrowser(url: string) {
        // const browser: ThemeableBrowserObject =
        this.themeableBrowser.create(url, '_blank', BrowserConfig.OPTIONS);

    }
    public imageFromBase64(base64: string) {
        return 'data:image/jpeg;base64,' + base64;
    }

    public openLocation(lat: number, lng: number) {
        this.launchNavigation.navigate([lat, lng]).then(
            () => { },
            () => { this.failedToOpenMap(); }
        );
    }
    private failedToOpenMap() {
        this.alertController.presentConfirm(
            this.ts.trPK('general', 'alert'),
            this.ts.trPK('error', 'map'),
            this.ts.trPK('general', 'ok'),
            () => {
                this.alertController.dismiss();
            }
        );
    }

    public evaluteDate(dateStr: string): string {
        if (dateStr) {
            const utc = parseInt(dateStr.substring(6, dateStr.length - 2), 10);
            if (utc) {
                const appoDate = new Date(utc);
                if ((appoDate instanceof Date) && !isNaN(appoDate.getTime())) {
                    return appoDate.toLocaleDateString();
                }
            }
        }
        return dateStr;
    }

    public evaluteDateAsObject(dateStr: string): Date {
        if (dateStr) {
            const utc = parseInt(dateStr.substring(6, dateStr.length - 2), 10);
            return new Date(utc);
        }
        return null;
    }

    public getDateISO(date: Date): string {
        return date.getFullYear().toString() + '-' +
            this.trailerZero(date.getMonth() + 1) + '-' +
            this.trailerZero(date.getDate());
    }

    public getTodayISO(): string {
        return this.getDateISO(new Date());
    }


    public getTimeISO(date: Date): string {
        return this.trailerZero(date.getHours()) + ':' +
            this.trailerZero(date.getMinutes()) + ':00';
    }

    public getDateTimeISO(date: Date): string {
        return this.getDateISO(date) + ' ' + this.getTimeISO(date);
    }

    public getDateTimeISOFromString(dateStr: string): string {
        const date = this.evaluteDateAsObject(dateStr);
        return this.getDateTimeISO(date) + ' ' + this.getTimeISO(date);
    }

    public getCurrentTimeISO(): string {
        return this.getTimeISO(new Date());
    }

    private trailerZero(value: number): string {
        const str = value.toString();
        return (str.length > 1) ? str : ('0' + str);
    }


    public hasData(array: any[]): boolean {
        return array != null && array.length > 0;
    }

    public extractNumber(message: string): string {
        if (message != null && message.length > 0) {
            let startIndex = null;
            let endIndex = message.length - 1;
            for (let i = 0; i < message.length; i++) {
                const code = message.charCodeAt(i);
                if (this.inNumberRange(code)) {
                    if (!startIndex) {
                        startIndex = i;
                    }
                } else {
                    if (startIndex) {
                        endIndex = i;
                        break;
                    }
                }
            }
            return startIndex ? message.substring(startIndex, endIndex) : '';
        }
        return null;
    }
    public inNumberRange(targetCode: number): boolean {
        const minDigit = '0'.charCodeAt(0);
        const maxDigit = '9'.charCodeAt(0);
        return (targetCode >= minDigit && targetCode <= maxDigit);
    }

    public enterPage() {
    }

    /*
    open calls
    */


    public openAppointments() {
        this.nav.navigateForward(['/eservices/appointments/home']);
        // this.router.navigateByUrl('/eservices/appointments/home');

    }

    public openHome() {
        this.nav.navigateRoot(['/home']);
        // this.nav.navigateByUrl('/home');

    }


    public reload(url: string, from: string) {
        console.log('force reload called from:' + from);
        // window.location.reload();
        location.href = url;
    }

    public navigateRoot(url: string) {
        this.nav.navigateRoot([url]);
    }


    public navigateForward(url: string) {
        this.nav.navigateForward([url]);
    }
    public navigateBack(url: string) {
        this.nav.navigateBack([url]);
    }
    public openEservices() {
        this.nav.navigateForward(['/eservices/home']);
        // this.router.navigateByUrl('/eservices/home');

    }
    public openBookings() {
        this.nav.navigateForward(['/eservices/booking/home']);
        // this.router.navigateByUrl('/eservices/bookings');
    }
    public openAppointmentDetails() {
        this.nav.navigateForward(['/eservices/appointments/detials']);
        // this.router.navigateByUrl('/eservices/appointments/detials');
    }

    public openApprovals() {
        this.nav.navigateForward(['/eservices/approvals']);
        // this.router.navigateByUrl('/eservices/approvals');

    }
    public openPrescriptions() {
        this.nav.navigateForward(['/eservices/prescriptions']);
        // this.router.navigateByUrl('/eservices/prescriptions');

    }
    public openPrescriptionReports() {
        this.nav.navigateForward(['/eservices/prescriptions/reports']);
        // this.router.navigateByUrl('/eservices/prescriptions/reports');

    }
    public openPrescriptionPharmaciesList() {
        this.nav.navigateForward(['/eservices/prescriptions/reports/pharmacies']);
        // this.router.navigateByUrl('/eservices/prescriptions/reports/pharmacies');

    }
    public openDoctorSchedule() {
        this.nav.navigateForward(['/eservices/doctors/schedule']);
        // this.router.navigateByUrl('/eservices/appointments/doctor-schedule');

    }

    public openRadiology() {
        this.nav.navigateForward(['/eservices/radiology']);
        // this.router.navigateByUrl('/eservices/radiology');
    }
    public openRadiologyReport() {
        this.nav.navigateForward(['/eservices/radiology/report']);
        // this.router.navigateByUrl('/eservices/radiology/report');
    }
    public openMyDoctors() {
        this.nav.navigateForward(['/eservices/doctors']);
    }
    public openDoctorProfile() {
        this.nav.navigateForward(['/eservices/doctors/profile']);
    }

    public openBookingCalendar() {
        this.nav.navigateForward(['/eservices/doctors/calendar']);
    }

    public openLabOrders() {
        this.nav.navigateForward(['/eservices/lab']);
        // this.router.navigateByUrl('/eservices/lab');
    }
    public openLabResult() {
        this.nav.navigateForward(['/eservices/lab/result']);
        // this.router.navigateByUrl('/eservices/lab/result');
    }

    public openEyePrescriptions() {
        this.nav.navigateForward(['/eservices/eye']);
    }

    public openEyeMeasurments() {
        this.nav.navigateForward(['/eservices/eye/measurments']);
    }

    public openBloodSugarGraph() {
        this.nav.navigateForward(['/eservices/tracker/blood-sugar/graph']);
    }

    public openBloodSugarAdd() {
        this.nav.navigateForward(['/eservices/tracker/blood-sugar/add']);
    }

    public openBloodPressureAdd() {
        this.nav.navigateForward(['/eservices/tracker/blood-pressure/add']);
    }

    public openBloodSugarRHMD() {
        this.nav.navigateForward(['/eservices/tracker/blood-sugar/rhmd']);
    }
    public openBloodSugarRHMDBL() {
        this.nav.navigateForward(['/eservices/tracker/blood-sugar/rhmd-bl']);
    }

    public openBloodSugarRHMDBLE() {
        this.nav.navigateForward(['/eservices/tracker/blood-sugar/rhmd-ble']);
    }
    public openBloodPressureGraph() {
        this.nav.navigateForward(['/eservices/tracker/blood-pressure/graph']);
    }

    public openWeightAdd() {
        this.nav.navigateForward(['/eservices/tracker/weight/add']);
    }

    public openWeightGraph() {
        this.nav.navigateForward(['/eservices/tracker/weight/graph']);
    }

    public openBookingDoctorsList() {
        this.nav.navigateForward(['/eservices/booking/doctors-list']);
    }
    public openBookingDentalComplains() {
        this.nav.navigateForward(['/eservices/booking/dental-complains']);
    }

    public openDocResponseDetail() {
        this.nav.navigateForward(['/eservices/doc-response/response-detail']);
    }
    public openInsurCardDetail() {
        this.nav.navigateForward(['/eservices/insur-cards/card-detail']);
    }
    public openUserAgreement() {
        this.nav.navigateForward(['/eservices/month-report/user-agreement']);
    }

    public openChildVaccineHome() {
        this.nav.navigateForward(['/eservices/child-vaccine/home']);
    }

    public openChildVaccineVaccineList() {
        this.nav.navigateForward(['/eservices/child-vaccine/vaccine-list']);
    }

    public openChildVaccineAddChild() {
        this.nav.navigateForward(['/eservices/child-vaccine/add-child']);
    }

    public openChildVaccineChildList() {
        this.nav.navigateForward(['/eservices/child-vaccine/child-list']);
    }

    public openAskDocRequest() {
        this.nav.navigateForward(['/eservices/ask-doc/ask-doc-request']);
    }

    public openNewMedReport() {
        this.nav.navigateForward(['/eservices/med-report/new-med-report']);
    }

    public openUserLogin() {
        console.log('now open login');
        this.nav.navigateForward(['/authentication/login']);
    }
    public openAgreement() {
        this.nav.navigateForward(['/authentication/agreement']);
    }
    public openUserRegister() {
        this.nav.navigateForward(['/authentication/register']);
    }
    public openUserForgot() {
        this.nav.navigateForward(['/authentication/forgot']);
    }

    public openFeedback() {
        this.nav.navigateForward(['/feedback/home']);
    }
    public openFeedbackStatusDetails() {
        this.nav.navigateForward(['/feedback/status-details']);
    }

    public navigateTo(url: string) {
        this.nav.navigateForward([url]);
    }


}
