import { Inject } from "@angular/core";
import { AuthService } from '../auth/auth.service';
import { HttpHeaders, HttpParams, HttpClient } from '@angular/common/http';
import * as signalR from "@aspnet/signalr";
import { Observable, BehaviorSubject } from "rxjs";
import { Store, select, UPDATE } from '@ngrx/store';
import { UPDATEE } from '../baseclass/UnifiedNotificationReducer';
import { UnifiedNotificationObject } from '../interface/UnifiedNotificationObject';
import { UnifiedNotificationObjectClass } from '../auth/UnifiedNotification.service';
import { Http } from '@angular/http';
import { Headers } from '@angular/http';
import { RequestOptions } from '@angular/http';
import { ConnectionIndicationService } from '../auth/ConnectionIndication.service';

//interface AppStateUnot {
//    unot: OcNotificationMod;
//}

export class OcNotificationMod {
    statusName: string;
    totalcount: number;
    instance: OcNotificationFigure[];
}


export class OcNotificationFigure {

    statusName: string;
    instanceCount: number;
}

export class OcBasedUnifiedNotificationService {
    connection: signalR.HubConnection;
    public notificationModSub: BehaviorSubject<OcNotificationMod>;
    totalcount: number;
    totalcount$: Observable<number>;
    notificationMod: OcNotificationMod;
    statustypecount: number;
    currentstatustypecount: number;
    constructor(private authService: AuthService,
        public http: HttpClient,
        public httpg: Http,
        @Inject('syncserviceurl') public syncserviceUrl: string
        //, private store: Store<AppStateUnot>
    ) {

        this.notificationModSub = new BehaviorSubject(<OcNotificationMod>{});



    }

    build() {
        // alert('sss');
        this.connection = new signalR.HubConnectionBuilder()
            .withUrl(this.syncserviceUrl + "NotificationHub",
                {
                    accessTokenFactory: () =>

                        this.authService.getAccessToken()
                })
            .build();

        ConnectionIndicationService.ConnectionStatusChanged.subscribe(online => {
            if (online) {
                this.start();
            } else {
                this.stop();

            }

        });


        this.connection.serverTimeoutInMilliseconds = 3600000;


        return this.connection;
    }

    on() {

        this.connection.on("IOcStatusNotification", data => {
            let status: string = data;
            this.UpdateCount(status);
        });


    }

    start() {
        // alert('sss3');
        this.connection.start().then(() => {
            console.log('OCStatus Notification connection started');
        }).catch(err => {
            // alert('Error while establishing connection');
        });


    }

    off() {
        this.connection.off("IOcStatusNotification");

    }
    stop() {

        this.connection.stop().then(() => {


        }).catch(function (err) {
            //   alert('Error while establishing connection');
        });

    }
    public InitiateCount(statuslist: string[]) {
        this.currentstatustypecount = 0;
        this.statustypecount = statuslist.length;
        this.totalcount = 0;
        // alert(statuslist.length);
        if (statuslist.length == 0) {
            this.notificationMod = <OcNotificationMod>{};
            this.notificationMod.totalcount = 0;
            this.notificationModSub.next(this.notificationMod);
        }
        else {
            for (let x in statuslist) {
                this.UpdateCount(statuslist[x]);
            }
        }
    }


    public UpdateCount(status: string) {

        this.StatusCount(status).subscribe(s => {
            // alert(s.text());
            var ss: number = JSON.parse(s.text());

            if (this.notificationMod == null) {
                this.notificationMod = <OcNotificationMod>{};
            }
            if (this.notificationMod.instance != null) {
            }
            else {
                this.notificationMod.instance = [];
            }
            var item = this.notificationMod.instance.find(x => x.statusName == status);
            if (item == null) {

                var newitem: OcNotificationFigure = { instanceCount: ss, statusName: status };
                this.totalcount += ss;
                this.notificationMod.totalcount = this.totalcount;
                this.notificationMod.instance.push(newitem);
            }
            else {
                var newitem: OcNotificationFigure = { instanceCount: ss, statusName: status };
                this.notificationMod.instance.splice(this.notificationMod.instance.findIndex(s => s.statusName == status), 1);
                this.notificationMod.instance.push(newitem);
                var countnew: number = 0;
                for (let x in this.notificationMod.instance) {
                    countnew += this.notificationMod.instance[x].instanceCount;
                }
                this.totalcount = countnew;
                this.notificationMod.totalcount = this.totalcount;
                // unotres.instance.push(newitem);
            }
            this.currentstatustypecount += 1;
            this.notificationMod.instance = this.notificationMod.instance.sort(
                (n1, n2) => {
                    return n2.instanceCount - n1.instanceCount;
                });
            this.notificationMod.statusName = status;
            this.notificationModSub.next(this.notificationMod);
            // this.store.dispatch({ type: UPDATEE, value: unotres });




        }
        );
    }

    public StatusCount(status: string) {

        let header = new Headers({ 'Content-Type': 'application/json', 'Authorization': this.authService.getAuthorizationHeaderValue() });
        header.append('OC', this.authService.getSelectedOc());
        var optionss = new RequestOptions({ headers: header });

        return this.httpg.get(this.syncserviceUrl + "api/Notification/GetOcUnifiedNotificationCount?status=" + status,
            optionss);
    }

    public GetNotificationList(status: string) {
        // console.log("456");
        let header = new Headers({ 'Content-Type': 'application/json', 'Authorization': this.authService.getAuthorizationHeaderValue() });
        header.append('OC', this.authService.getSelectedOc());
        var optionss = new RequestOptions({ headers: header });

        return this.httpg.get(this.syncserviceUrl + "api/Notification/GetOcUnifiedNotificationObjects?status=" + status,
            optionss);
    }

    public GetAllNotificationList(): Observable<UnifiedOcNotificationObjectClass[]> {
        var optionss = {
            headers: new HttpHeaders({
                'Content-Type': 'application/json'
                , 'Authorization': this.authService.getAuthorizationHeaderValue()
                , 'OC': this.authService.getSelectedOc()
            }),
            params: new HttpParams()
        };

        return this.http.get<UnifiedOcNotificationObjectClass[]>(this.syncserviceUrl
            + "api/Notification/GetOcAllUnifiedNotificationList",
            optionss);
    }

    public GetAllUnifiedNotificationList(): Observable<UnifiedOcNotificationObjectClass[]> {
        var optionss = {
            headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': this.authService.getAuthorizationHeaderValue() }),
            params: new HttpParams()
        };

        return this.http.get<UnifiedOcNotificationObjectClass[]>(this.syncserviceUrl + "api/Notification/GetAllUnifiedNotificationList",
            optionss);
    }

    public GetStatusList() {
        var optionss = {
            headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': this.authService.getAuthorizationHeaderValue() }),
            params: new HttpParams()
        };

        return this.http.get<string[]>(this.syncserviceUrl + "api/Notification/GetOcUnifiedNotificationStatus",
            optionss);
    }
}



export class UnifiedOcNotificationObjectClass extends UnifiedNotificationObjectClass {

    oclist: string[]



}
