import { Message } from '@angular/compiler/src/i18n/i18n_ast';
import { 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 { 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'
})
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;

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

    ngOnInit(): void {
        // Subscribe to msgReceived of iframeMsgHandlingService to get JobId
        console.log('About to subscribe in Admin');
        this.subscriptions.push(this.iframeMsgHandlingService.msgReceived.subscribe(
            (message: any) => {
                console.log('Admin Subscribed', message);
                if (!message || !message.name) {
                    return;
                }

                if (message.name !== 'HiringTeamChat' || message.message === null) {
                    return;
                }
                const msg = JSON.parse(message.message);
                console.log('Admin Parsed', msg);
                // Show Chat bubble if message service allows
                this.showBubble = true;
            }
        ));

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