import { Injectable, NgZone } from '@angular/core';
// import { Push, PushObject, PushOptions } from '@ionic-native/push/ngx';
import { CommonService } from '../common/common.service';
import { TranslatorService } from '../translator/translator.service';
import { NotificationModel } from './models/notification.model';
import { SharedDataService } from '../shared-data-service/shared-data.service';
import { ConnectorService } from '../connector/connector.service';
//import { Response } from '../models/response';
import { Response } from 'src/app/hmg-common/services/models/response';
import { RegisterAuthenticatedUserRequest } from './models/register-authenticated-user.request';
import { Platform, Events } from '@ionic/angular';
import { RegisterNormalUserRequest } from './models/register-normal-user.request';
import { AuthenticationService } from '../authentication/authentication.service';
// import { AppointmentModel } from 'src/app/eservices/appointments/service/models/appointment.model';
import { SessionModel } from './models/session.model';
import { AuthenticatedUser } from '../authentication/models/authenticated-user';
// import { NotificationsCenterService } from 'src/app/eservices/notifications-center/service/notifications-center.service';
// import { NotificationsComponent } from 'src/app/eservices/notifications-center/notifications/notifications.component';
import {OneSignal} from '@ionic-native/onesignal/ngx'
@Injectable({
    providedIn: 'root'
})
export class PushService {
    private static notLoggedInUserURL = 'Services/MobileNotifications.svc/REST/PushNotification_InsertPatientDeviceInformation';
    private static loggedInUserURL = 'Services/MobileNotifications.svc/REST/Insert_PatientMobileDeviceInfo';
    public static SENDER_ID = '679409052782';//'815750722565';

    public static CHANNEL_ID = '679409052782';//'815750722565';
    constructor(
        // public push: Push,
        public cs: CommonService,
        public ts: TranslatorService,
        public sharedService: SharedDataService,
        public con: ConnectorService,
        private platform: Platform,
        private authService: AuthenticationService,
        public ngZone: NgZone,
        // public notifyService: NotificationsCenterService,
        public events: Events,
        private oneSignal: OneSignal,


    ) { }

    public startReceiving() {
        this.processStartReceiving();
    }
    private processStartReceiving1() {
        // if (this.cs.isCordova()) {
        //     this.stopNotifications(() => {
        //         this.push.hasPermission()
        //             .then((res: any) => {
        //                 if (res.isEnabled) {
        //                     this.createChannel();
        //                 } else {
        //                     this.cs.presentAlert(this.ts.trPK('push', 'no-permiss'));
        //                 }
        //             });
        //     });
        // }
    }

    private createChannel() {
        // Create a channel (Android O and above). You'll need to provide the id, description and importance properties.
        // this.push.createChannel({
        //     id: PushService.CHANNEL_ID,
        //     description: 'HMG push notifications',
        //     importance: 3
        // }).then(() => {
        //     this.initialize();
        // });
    }

    private initialize() {
        // const options: PushOptions = {
        //     android: {
        //         senderID: PushService.CHANNEL_ID,
        //         sound: true,
        //         forceShow: true
        //     },
        //     ios: {
        //         alert: true,
        //         badge: true,
        //         sound: true
        //     },
        //     windows: {},
        //     browser: {
        //         pushServiceURL: 'http://push.api.phonegap.com/v1/push'
        //     }
        // };
        // const pushObject: PushObject = this.push.init(options);
        // pushObject.on('notification').subscribe((notification: any) => {
        //     this.processNotification(notification);
        // });

        // pushObject.on('registration').subscribe((data: any) => {
        //     this.registerInBackend(data);
        // });

        // pushObject.on('error').subscribe(error => console.error('Error with Push plugin', error));

    }

    private processNotification(data: any) {
        const notification = new NotificationModel();
        this.cs.setBadge(data.additionalData.badgenumber - 1);
        notification.Id = data.additionalData.msgID ? data.additionalData.msgID : data.additionalData.notfID;
        notification.count = data.count;
        notification.Message = data.message;
        notification.AppointmentNo = data.additionalData.AppointmentNo;
        notification.ProjectID = data.additionalData.ProjectID;
        notification.NotificationType = data.title;
        this.processNotificationType(notification, data);
    }

    private processNotificationType(notification: NotificationModel, data: any) {
        this.setAsReadNotification(notification);
        const type = Number(data.additionalData.NotificationType);
        if (type === NotificationModel.TYPE_APPOINTMENT) {
            this.sharedService.setSharedData(notification, NotificationModel.SHARED_DATA);
           // this.ngZone.run(() => this.cs.openAppointmentDetails());
        } else if (type === NotificationModel.TYPE_CONFERENCE) {
            const session = data.additionalData.sessionId;
            // console.log('session Id Recieved>>>>>'+ session);
            this.sharedService.setSharedData( new SessionModel(session) , SessionModel.SHARED_DATA);
           // this.ngZone.run( () => this.cs.openConference() );
        } else {
            if (type === NotificationModel.TYPE_VIDEO) {
                notification.MessageType = 'video';
                notification.MessageTypeData = data.additionalData.videoUrl;
            } else if (type === NotificationModel.TYPE_IMAGE) {
                notification.MessageType = 'image';
                notification.MessageTypeData = data.additionalData.picture;
            } else {
                notification.MessageType = 'text';
            }
            this.sharedService.setSharedData(notification, NotificationModel.SHARED_DATA);
            //this.ngZone.run(async () => this.cs.openNotificationDetails());
        }
    }

    private setAsReadNotification(notification: NotificationModel) {
        notification.IsRead = true;
        // this.notifyService.setNotificationRead(notification, () => {
        // }).subscribe((result: Response) => {
        //     if (this.cs.validResponse(result)) {
        //         this.events.publish( NotificationsCenterService.NOTIFICATIONS_COUNT_EVENT, notification.count);
        //     }
        // });


    }
    public stopNotifications(done: any) {
        // Delete a channel (Android O and above)
        // if (this.cs.isCordova()) {
        //     this.push.deleteChannel(PushService.CHANNEL_ID).then(() => {
        //         done();
        //     });
        // }
    }

    private registerInBackend(data: any) {
        console.log("registerInBackend");
        if (this.authService.isAuthenticated()) {
            this.registerAuthenticatedUser(data.registrationId);
        } else {
            this.registerNotAuthenticatedUser(data.registrationId);
        }
    }


    private registerAuthenticatedUser(deviceToken: any) {
        const request = new RegisterAuthenticatedUserRequest();
        this.authService.authenticateRequest(request);
        request.DeviceToken = deviceToken;
        request.DeviceType = this.getDeviceType();
        const user = this.authService.getAuthenticatedUser();
       // request.PatientMobileNumber = user.MobileNo;
        //request.NationalID = user.IdentificationNo;
        request.Gender = user.Gender;
        request.PatientID = user.PatientID;
       // request.PatientOutSA = user.PatientOutSA ? 1 : 0;
        //request.LoginType = user.biometricEnabled ? 2 : 1; // 1 sms , 2 touch id
        request.MACAddress = '00:00:00:00:00:00';
        return this.con.postNoLoad(PushService.loggedInUserURL, request
            , () => { }).subscribe((result: Response) => {
                if (this.cs.validResponse(result)) {
                    this.authService.setDeviceToken(deviceToken);
                }
            });
    }


    private registerNotAuthenticatedUser(deviceToken: any) {
        const request = new RegisterNormalUserRequest();
        this.authService.setPublicFields(request);
        request.ChannelID = request.Channel;
        request.DeviceToken = deviceToken;
        request.DeviceType = this.getDeviceType();
        return this.con.postNoLoad(PushService.notLoggedInUserURL, request
            , () => { }).subscribe((result: Response) => {
                if (this.cs.validResponse(result)) {
                    console.log('device token:' + deviceToken);
                }
            });
    }

    private getDeviceType(): string {
        return this.platform.is('ios') ? 'Iphone' : 'Android';
    }



    private processStartReceiving() {
        console.log('processStartReceiving');

        console.log("processStartReceiving openConference");
        this.oneSignal.startInit('8d9b8313-0365-4934-a2a9-fdee5aeac66e', PushService.SENDER_ID);
        this.oneSignal.inFocusDisplaying(this.oneSignal.OSInFocusDisplayOption.Notification);
        this.oneSignal.handleNotificationReceived().subscribe(data => this.onPushReceived(data.payload));
        this.oneSignal.handleNotificationOpened().subscribe(data => this.onPushOpened(data.notification.payload));
        console.log("this.oneSignal: "+ this.oneSignal.getIds());
        this.oneSignal.endInit();
        this.oneSignal.getIds().then(result => {
            console.log("result.userId: " +result.userId);
    
            //there is no part for notLoggedInUserURL () as patient app
            if(result.userId){
            this.cs.sharedService.setSharedData(result.userId, AuthenticationService.DEVICE_TOKEN);
            localStorage.setItem("deviceToken", result.userId);

            }
           
          this.registerInBackend(result.userId);
            }, err => {
                console.log("getIds() error: "+err);

        });

        // if (this.cs.isCordova()) {
        //     console.log('Notification Channel Called');

        //     if (this.platform.is('android')) {
        //         this.stopNotifications(() => {

        //         });
        //     } else {
        //         //initialize code
        //     }
        // }
    }
    public onPushReceived(payload: any) {
        console.log(JSON.parse(JSON.stringify(payload)));
        console.log('Push-Received whole payload: ' + payload);
    }

    public onPushOpened(payload: any) {
        console.log(JSON.parse(JSON.stringify(payload)));
        console.log('Push-opened whole payload: ' + payload);
        console.log("onPushOpened openConference");
        this.processNotification(payload);
    }



}
