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: Array<Message> = [];
    jobApplicationID: 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(): void {
        this.subscriptions.push(
            this.msgsService.successMsgsUpdated.subscribe(
                data => {
                    this.successMsgs = data;
                }
            )
        );

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

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

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

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

        this.applicantPortalLayoutService.reloadApplicantUserDetails(this.jobApplicationID);
    }

    subscribeToUserData(): void {
        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(): void {
        this.utilsService.unsubscribeSubscriptions(this.subscriptions);
    }
}
