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 { 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: Message[] = [];
    clientName: string;
    userName: string;
    homeURL: string;
    companyName: string;
    companyUser: any;
    selectedTeam: any;
    selectedTeamID: string;
    redirectURL: string;
    createJobDisabled : boolean;
    isStandardUser: boolean;
    hiringTeams: any[];
    userMenu: any;
    sidebarMenu: any;
    select2Options = {
        minimumResultsForSearch: Infinity
    }

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

    ngOnInit() {
        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() {
        this.loadData();
    }

    loadData() {
        this.userService.reloadUserDetails();
        this.msgsService.clearErrorMessages();
        
        this.adminPortalLayoutService.reloadAdminUserDetails();
        this.loadMenu();
        this.userName   =   this.userService.getUsername();
    }

    subscribeToUserData() {
        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(let 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() {
        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 (
                data => {
                    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() {
        this.utilsService.unsubscribeSubscriptions(this.subscriptions);
    }
}
