import { Message } from '@angular/compiler/src/i18n/i18n_ast';
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { Subscription } from 'rxjs';
import { MsgsService } from '../../../oneit/services/msgs.service';
import { UserService } from '../../../oneit/services/user.service';
import { UtilsService } from '../../../oneit/services/utils.service';
import { ApplicantPortalLayoutService } from './applicant-portal-layout.service';

@Component({
    selector: 'app-applicant-portal-layout',
    templateUrl: './applicant-portal-layout.component.html'
})
export class ApplicantPortalLayoutComponent implements  OnInit, OnDestroy {

    showLoader: boolean;
    subscriptions: Array<Subscription> = [];
    successMsgs: Message[] = [];
    pageTitle: string;
    jobId: string;
    key: string;
    year = new Date().getFullYear();
    
    constructor(
        private msgsService: MsgsService,
        private userService: UserService,
        private utilsService: UtilsService,
        private titleService: Title,
        private router: Router,
        private activatedRoute: ActivatedRoute,
        private applicantPortalLayoutService: ApplicantPortalLayoutService,
    ) { }

    ngOnInit() {
        this.subscriptions.push(
            this.msgsService.successMsgsUpdated.subscribe(
                data => {
                    this.successMsgs = data;
                }
            )
        );

        this.subscriptions.push(this.activatedRoute.params
            .subscribe(
                (params: Params) => {
                    if (params.job) {
                        this.jobId = params.job;
                    }
                    if (params.key) {
                        this.key = params.key;
                    }
                    this.loadData();
                }
            )
        );

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

    onRouteUpdate() {
        this.loadData();
    }

    loadData() {
        this.userService.reloadUserDetails();
        this.msgsService.clearErrorMessages();
        
        this.applicantPortalLayoutService.reloadApplicantUserDetails(this.jobId, this.key);
    }

    subscribeToUserData() {
        this.subscriptions.push(this.applicantPortalLayoutService.userDataUpdated.subscribe(
            data => {
                if(data.PageTitle) {
                    this.titleService.setTitle(data.PageTitle);
                } else {
                    this.titleService.setTitle('Matchd');
                }
            },
            error => {
                this.utilsService.handleError(error);
            }
        ));
    }

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