import { Injectable, NgZone } from '@angular/core';
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 '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 { SessionModel } from './models/session.model';
import { FirebaseX } from '@ionic-native/firebase-x/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 cs: CommonService,
        public ts: TranslatorService,
        public sharedService: SharedDataService,
        public con: ConnectorService,
        private platform: Platform,
        private authService: AuthenticationService,
        public ngZone: NgZone,
        public events: Events,
        public firebasex: FirebaseX
    ) { }

    public startReceiving() {
        console.log("startReceiving");
        this.firebasex.hasPermission().then(hasPermission => {
            if (!hasPermission) {
                this.firebasex.grantPermission().then(hasPermission => {
                    console.log("Permission was " + (hasPermission ? "granted" : "denied"));
                    this.processStartReceivingWithFirebase();
                }); 
            } else {
                this.processStartReceivingWithFirebase();
            }
        });     
    }​​
        

    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);
        } else if (type === NotificationModel.TYPE_CONFERENCE) {
            const session = data.additionalData.sessionId;
            this.sharedService.setSharedData( new SessionModel(session) , SessionModel.SHARED_DATA);
        } 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);
        }
    }

    private setAsReadNotification(notification: NotificationModel) {
        notification.IsRead = true;
    }

    private registerInBackend(data: any) {
       console.log('firebasex Token ID: ' + data);
        if (data) {
            this.cs.sharedService.setSharedData(data, AuthenticationService.DEVICE_TOKEN);
            localStorage.setItem('deviceToken', data);
        }
    }


    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 processStartReceivingWithFirebase() {
        console.log("processStartReceivingWithFirebase");
        this.firebasex.getToken().then(token => {
           // alert("token: "+ token);
            this.cs.sharedService.setSharedData(token, "new-device-token");
            localStorage.setItem('deviceToken', token);
            this.cs.setDeviceToken(token); //last way to set the device Token to get it through getDeviceToken
            this.registerInBackend(token);
        }).catch(error => console.error('Error getting token', error));
    }

    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);
    }
}
