import { OnInit } from "@angular/core";
import { Http } from '@angular/http';
// import { MessageService, Message } from "primeng/api";
import { MessageService } from '../common/messageservice';
import { ConfirmationService } from '../../../primeng/api';
import { BaseService } from '../baseclass/BaseService';
import { BlockUI, NgBlockUI } from 'ng-block-ui';
import { Observable, BehaviorSubject } from "rxjs";
import { AuthService } from '../auth/auth.service';
import { RequireInteractiveControl } from "../interface/Interactive Component/RequireInteractiveControl";
import { WebNotificationService } from '../auth/webNotification.service';
import { ConnectionIndicationService } from '../auth/ConnectionIndication.service';
import { RequireOcList } from '../interface/Interactive Component/RequireOc';
import { LocalContainerObject } from '../interface/Interactive Component/LocalContainerObject';
import { FormGroup } from "@angular/forms";
// import { MessageService } from "primeng/components/common/api";

export class BaseComponent<T extends RequireInteractiveControl> implements OnInit {
    @BlockUI() baseblockUI: NgBlockUI;
    userform: FormGroup;
    displayDialog: boolean;
    public mode: string;
    public baseu: string;
    public generalhttp: Http;
    loading: boolean = false;
    public selectedObject: T;
    public objectlist: T[];
    public obvobjlist: BehaviorSubject<T[]>;
    public isnewobject: boolean;
    //   public  actionitems:string[] =["Insert","Delete","Update"];
    constructor(
        public confirmationService: ConfirmationService,
        public webNotificationservice: WebNotificationService
        , public messageService: MessageService
        , public objectservice: BaseService<T>
        , public objectname: string
        , public authService: AuthService
        , public actionitems: string[] = ["Insert", "Delete", "Update"]
        , public blockUiControl: boolean = false,
        public SelectedOcChanged: boolean = false
    ) {
        this.obvobjlist = new BehaviorSubject<T[]>([]);

    }



    ngOnInit(): void {
        let callback = (data: any, typestr: string): void => { this.OnReceiveUpdate(data); };
        this.webNotificationservice.on(callback, this.objectname);
        this.ngOnInitLocal();

        // if(this.SelectedOcChanged)
        {
            // console.log("if(this.SelectedOcChanged)");
            this.authService.SelectedOcChanged.subscribe(s => {
                // console.log("if(this.SelectedOcChanged1)");
                this.list();
            });
        }
        // else
        // if(!this.SelectedOcChanged)
        // {
        //   console.log("if(this.SelectedOcChanged2)");
        //   this.list();
        // }
        ConnectionIndicationService.ConnectionStatusChanged.subscribe(online => {
            if (online) {

                this.list();

            }

        });
    }
    ngOnDestroy() {
        this.webNotificationservice.off();
        if (this.blockUiControl) {
            this.baseblockUI.stop();
        }
        this.objectlist = [];
    }
    ngOnInitLocal() {

    }
    list() {
        if (this.blockUiControl) {
            this.baseblockUI.start("Loading List...");
        }

        this.loading = true;
        this.objectservice.Get().subscribe(obj => {
            console.log(obj);
            this.objectlist = obj;
            this.obvobjlist.next(obj);
            this.baseblockUI.stop();
            this.loading = false;
        }, error => {
            console.error(error);
            this.loading = false;
        }
        );
    }
    instanceOfRequireOcList(object: any): object is RequireOcList {
        return 'ocStrList' in object;
    }
    OnReceiveUpdate(lco: LocalContainerObject) {
        console.log(lco);
        // this.messageService.add({severity:'Info', summary:'Info', detail:lco.objectUniqueId});
        if (lco.ocList != null && lco.ocList.length > 0) {
            if (!lco.ocList.some(s => s == this.authService.getSelectedOc())) {
                return;
            }
        }
        if (this.selectedObject != null && lco.objectUniqueId == this.selectedObject.id) {
            // var actionitems:string[] =["Insert","Delete","Update"]; 
            if (this.actionitems.includes(lco.action)) {
                this.messageService.add({ severity: 'Info', summary: 'Info', detail: 'The list will updated, please close dialog' });
                this.list();
                this.selectedObject.isLocked = true;
            }
        }
        else {
            // var actionitems:string[] =["Insert","Delete","Update"]; 
            if (this.actionitems.includes(lco.action)) {
                this.messageService.add({ severity: 'Info', summary: 'Info', detail: 'The list is updated, system will now refresh' });
                this.list();
            }

        }
    }




    onRowSelect(event: any, field: string) {

        switch (field) {
            case "onRowSelect": {
                this.edit(event);
                break;
            }
            // case "onAdopterSelect": { 
            //   this.onSetPolicy(event);
            //   break; 
            // } 
            // case "deleteRecord": { 
            //   this.deleteRecord(event);
            //   break; 
            // } 
            default: {
                console.log("Invalid choice");
                break;
            }
        }

    }

    cloneObj(c: any): void { }

    getAllDropdownList() { }

    edit(event) {
        this.baseblockUI.start("Loading...");
        this.getAllDropdownList();
        this.objectservice.GetById(event.id).subscribe(res => {
            try {
                if (res != null) {
                    console.log(res);
                    this.isnewobject = false;
                    this.selectedObject = res;
                    this.cloneObj(res);
                    this.displayDialog = true;

                }
                else {
                    this.messageService.add({
                        severity: 'error', summary: 'Error',
                        detail: "Object not found"
                    });
                    this.messageService.add({
                        severity: 'error', summary: 'Error',
                        detail: "Object not found", key: 'fixtop'
                    });
                    return;
                }
            } catch (error) {
                this.messageService.add({
                    severity: 'error', summary: 'Error',
                    detail: error
                });
                this.messageService.add({
                    severity: 'error', summary: 'Error',
                    detail: error, key: 'fixtop'
                });
            }
            this.baseblockUI.stop();
        });
    }

    submitObject(editObject: T): T {

        return editObject;
    }

    exeSubmit(value: string) {
        console.log(this.userform.value);
        let editObject: T = this.userform.value;

        editObject = this.submitObject(editObject);

        if (this.isnewobject) {
            this.baseblockUI.start("Loading...");
            this.objectservice.Create(editObject)
                .subscribe(res => {
                    this.saved(res);
                    this.baseblockUI.stop();
                });
        }
        else {
            if (!this.selectedObject.isLocked) {
                this.baseblockUI.start("Loading...");
                this.objectservice.Update(editObject)
                    .subscribe(res => {
                        this.saved(res);
                        this.baseblockUI.stop();
                    });
            }
            else {
                this.messageService.add({
                    severity: 'Info', summary: 'Info',
                    detail: "The object is updated, pelase refresh the page."
                });
                return;
            }
        }
    }

    onSubmit(value: string) {
        if (this.isnewobject) {
            this.exeSubmit("");
            return;
        }
        // this.displayDialog = false;
        this.confirmationService.confirm({
            message: 'Do you want to save and resync this record?',
            header: 'Confirmation',
            icon: 'pi pi-info-circle',
            accept: () => {
                this.exeSubmit("");
            },
            reject: () => {
                this.messageService.add({
                    severity: 'info', summary: 'Rejected',
                    detail: 'You have rejected'
                });
            }
        });
    }

    saved(resp: any) {
        console.log('saved');
        console.log(resp);
        if (resp == null) { return; }
        if (!resp.synced) {
            this.messageService.add({
                severity: 'error', summary: 'Error',
                detail: resp.errorMessage
            });
            this.messageService.add({
                severity: 'error', summary: 'Error',
                detail: resp.errorMessage, key: 'fixtop'
            });
            return;
        }

        // let objs = [...this.objectlist];

        this.selectedObject = null;
        this.displayDialog = false;

        if (this.isnewobject) {
            try {
                this.isnewobject = false;
                this.messageService.add({ severity: 'success', summary: 'Success', detail: 'Record Saved' });
                // objs.push(resp);
            } catch (error) {
                console.log("error: " + error);
                return;
            }
        }
        else {
            try {
                this.messageService.add({ severity: 'success', summary: 'Success', detail: 'Record Updated' });
                // objs[this.objectlist.indexOf(this.selectedObject)] = resp;
            } catch (error) {
                console.log("error: " + error);
                return;
            }
        }

        // this.list();
        // this.objectlist = objs;
    }

    exeDeleteAction() {
        if (this.selectedObject == null) {
            this.messageService.add({ severity: 'error', summary: 'Error', detail: 'No record seleted' });
            this.messageService.add({ severity: 'error', summary: 'Error', detail: 'No record seleted', key: 'fixtop' });
            return;
        }
        if (this.selectedObject.isLocked) {
            this.messageService.add({
                severity: 'Info', summary: 'Info',
                detail: "The object is updated, pelase refresh the page."
            });
            return;
        }
        this.deleteServices();
    }

    deleteServices() {
        this.objectservice.Delete(this.selectedObject)
            .subscribe(res => {
                if (res == null) { return; }

                // this.removeList(res)
                this.list();

                this.messageService.add({ severity: 'success', summary: 'Success', detail: 'Action Deleted' });
            });
    }

    removeList(resp: any) {
        // console.log(resp);
        if (resp == null) { return; }

        this.messageService.add({ severity: 'success', summary: 'Success', detail: 'Record Deleted' });
        let index = this.objectlist.indexOf(this.selectedObject);
        this.objectlist = this.objectlist.filter((val, i) => i != index);
        this.selectedObject = null;
        this.displayDialog = false;
    }

    confirmDeleteTittle(): string {
        return '';
    }

    confirmDelete() {
        this.displayDialog = false;
        let Seleted = this.confirmDeleteTittle(); //  this.selectedObject.string1? this.selectedObject.string1 : '';
        this.confirmationService.confirm({
            message: 'Do you want to delete this record?'
                + ' (Selected record: ' + Seleted + ')',
            header: 'Delete Confirmation',
            icon: 'pi pi-info-circle',
            accept: () => {
                this.exeDeleteAction();
            },
            reject: () => {
                this.messageService.add({
                    severity: 'info', summary: 'Rejected',
                    detail: 'You have rejected'
                });
            }
        });
    }

    deleteRecord(row): void {
        let Seleted = this.confirmDeleteTittle(); //row.string1? row.string1 : '';
        this.confirmationService.confirm({
            message: 'Do you want to delete this record?'
                + ' (Selected record: ' + Seleted + ')',
            header: 'Delete Confirmation',
            icon: 'pi pi-info-circle',
            accept: () => {
                this.selectedObject = row;
                this.exeDeleteAction();
            },
            reject: () => {
                this.messageService.add({
                    severity: 'info', summary: 'Rejected',
                    detail: 'You have rejected'
                });
            }
        });
    }

}
