import { Message } from '@angular/compiler/src/i18n/i18n_ast';
import { ChangeDetectorRef, Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { Router } from '@angular/router';
import { BsModalService } from 'ngx-bootstrap/modal';
import { DeviceDetectorService } from 'ngx-device-detector';
import { Subscription } from 'rxjs';
import { environment } from '../../../../environments/environment';
import { AppService } from '../../../app.service';
import { IframeMsgHandlingService } from '../../../oneit/services/iframe-msg-handling.service';
import { MsgsService } from '../../../oneit/services/msgs.service';
import { UserService } from '../../../oneit/services/user.service';
import { UtilsService } from '../../../oneit/services/utils.service';
import { AdminPortalLayoutService } from './admin-portal-layout.service';

@Component({
    selector: 'app-admin-portal-layout',
    templateUrl: './admin-portal-layout.component.html',
    styleUrls: ['./admin-portal-layout.component.scss']
})
export class AdminPortalLayoutComponent implements OnInit, OnDestroy {

    @ViewChild('reachedCapModal') reachedCapModal;
    @ViewChild('trialNotAllowedModal') trialNotAllowedModal;
    showLoader: boolean;
    subscriptions: Array<Subscription> = [];
    successMsgs: Array<Message> = [];
    clientName: string;
    userName: string;
    homeURL: string;
    companyName: string;
    companyUser: any;
    selectedTeam: any;
    selectedTeamID: string;
    redirectURL: string;
    createJobDisabled: boolean;
    isStandardUser: boolean;
    hiringTeams: Array<any>;
    userMenu: any;
    sidebarMenu: any;
    select2Options = {
        minimumResultsForSearch: Infinity
    };
    showChat = false;
    showBubble = false;
    jobApplicationID: string;

    constructor(
        private deviceService: DeviceDetectorService,
        private msgsService: MsgsService,
        private userService: UserService,
        private adminPortalLayoutService: AdminPortalLayoutService,
        private utilsService: UtilsService,
        private appService: AppService,
        private titleService: Title,
        private router: Router,
        private modalService: BsModalService,
        private iframeMsgHandlingService: IframeMsgHandlingService,
        private changeDetector: ChangeDetectorRef
    ) {
    }

    ngOnInit(): void {
        // Subscribe to msgReceived of iframeMsgHandlingService to get JobId
        this.subscriptions.push(this.iframeMsgHandlingService.msgReceived.subscribe(
            (message: any) => {
                if (!message || !message.name) {
                    return;
                }

                if (message.name === 'HiringTeamChat') {
                    if(!message.message) {
                        this.jobApplicationID = null;
                        this.showBubble = false;
                    } else {
                        const msg = JSON.parse(message.message);
                        this.jobApplicationID = msg.JobApplicationID;
                        // Show Chat bubble if message service allows
                        this.showBubble = true;
                    }
                } else if (message.name === 'DisableCreateJobButton') {
                    if(message.message != this.createJobDisabled) {
                        this.createJobDisabled  = message.message;
                        this.changeDetector.detectChanges();
                    }
                }
            }
        ));

        if (this.deviceService.isMobile()) {
            window.location.href = `${environment.baseUrl}extensions/adminportal/responsive_alert.jsp`;
        }
        this.subscriptions.push(
            this.msgsService.successMsgsUpdated.subscribe(
                data => {
                    this.successMsgs = data;
                }
            )
        );

        this.titleService.setTitle('Matchd');
        this.subscribeToUserData();
        this.loadData();
    }

    onRouteUpdate(): void {
        this.loadData();
    }

    loadData(): void {
        this.userService.reloadUserDetails();
        this.msgsService.clearErrorMessages();

        this.adminPortalLayoutService.reloadAdminUserDetails();
        this.loadMenu();
        this.userName = this.userService.getUsername();
    }

    subscribeToUserData(): void {
        this.subscriptions.push(this.adminPortalLayoutService.userDataUpdated.subscribe(
            data => {
                this.clientName = data.ClientName || this.userService.getFullName();
                this.homeURL = data.HomeURL;
                this.companyName = data.CompanyName;
                this.companyUser = data.CompanyUser;
                this.selectedTeam = data.SelectedTeam;
                this.selectedTeamID = data.SelectedTeam ? data.SelectedTeam.ObjectID : null;
                this.hiringTeams = data.HiringTeams;
                this.createJobDisabled = data.CreateJobDisabled;

                if (this.hiringTeams) {
                    // this.utilsService.addNULLOptionForAssocSelect(this.hiringTeams, 'HiringTeamName');
                    for (const hiringTeam of this.hiringTeams) {
                        hiringTeam.id = hiringTeam.ObjectID;    // Added for select2
                        hiringTeam.text = hiringTeam.HiringTeamName;
                    }
                }

                if (this.companyName) {
                    this.titleService.setTitle(`Matchd - ${this.companyName}`);
                } else {
                    this.titleService.setTitle('Matchd');
                }
            },
            error => {
                this.utilsService.handleError(error);
            }
        ));
    }

    loadMenu(): void {
        this.adminPortalLayoutService.getAdminMenu()
            .subscribe(
                data => {
                    this.userMenu = data.userMenu;
                    this.sidebarMenu = data.sidebarMenu;
                },
                error => {
                    this.utilsService.handleError(error);
                }
            );
    }

    selectedTeamChanged(event: any): void {
        this.selectedTeamID = event.value;

        this.showLoader = true;
        this.subscriptions.push(
            this.adminPortalLayoutService.selectHiringTeam(this.selectedTeamID)
                .subscribe(
                    () => {
                        this.router.navigate(['admin/iframe-page', this.homeURL]);
                        this.loadData();
                        this.showLoader = false;
                    },
                    error => {
                        this.showLoader = false;
                        this.utilsService.handleError(error);
                    }
                )
        );
    }

    createJobClicked(): void {
        this.showLoader = true;
        this.subscriptions.push(
            this.adminPortalLayoutService.createJob(this.selectedTeamID, this.companyUser)
                .subscribe(
                    data => {
                        if (data.AllowCreateJob) {
                            if (data.AllowCreateJob === 'REACHED_CAP') {
                                this.modalService.show(this.reachedCapModal);
                            } else if (data.AllowCreateJob === 'TRIAL') {
                                this.modalService.show(this.trialNotAllowedModal);
                            } else {

                                this.router.navigate(['admin/iframe-page', data.redirectURL]);
                            }
                            this.isStandardUser = data.StandardUser;
                            this.redirectURL = data.redirectURL;
                            this.showLoader = false;
                        }
                    },
                    error => {
                        this.showLoader = false;
                        this.utilsService.handleError(error);
                    }
                )
        );
    }

    ngOnDestroy(): void {
        this.utilsService.unsubscribeSubscriptions(this.subscriptions);
    }
}
