import { Component, OnInit, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { ConfirmationService } from 'primeng/api';
import { Subscription } from 'rxjs';
import { environment } from '../../../environments/environment';
import { FIELDS } from '../../constants';
import { SaveService } from '../../oneit/services/save.service';
import { UtilsService } from '../../oneit/services/utils.service';
import { Candidate } from '../search-applicants/search-applicants.model';
import { SearchApplicantService } from '../search-applicants/search-applicants.service';

@Component({
    selector: 'app-edit-applicant',
    templateUrl: './edit-applicant.component.html',
    styleUrls: ['./edit-applicant.component.css']
})
export class EditApplicantComponent implements OnInit {

    subscriptions: Array<Subscription> = [];
    @ViewChild('form') form: NgForm;

    saveDropdown = [{
        label: 'Save & Back', icon: 'ui-icon-refresh', command: () => { this.saveApplicants(false); }
    }]

    readonly FIELDS = FIELDS;

    applicant: Candidate = new Candidate();
    baseUrl = environment.baseUrl;
    showLoader: boolean = false;
    cols = [
        { field: 'Job.HiringTeam.Company.CompanyName', header: 'Customer', width: '18%', noSort: false, noFilter: false },
        { field: 'Job.HiringTeam.HiringTeamName', header: 'Hiring Team', width: '18%', noSort: false, noFilter: false },
        { field: 'Job.JobTitle', header: 'Job', width: '18%', noSort: false, noFilter: false },
        { field: 'CV', header: 'CV', width: '23%', noSort: true, noFilter: true },
        { field: 'CoverLetter', header: 'Cover Letter', width: '23%', noSort: true, noFilter: true },
    ];

    constructor(
        private activatedRoute: ActivatedRoute,
        private SearchApplicantService: SearchApplicantService,
        private utilsService: UtilsService,
        private saveService: SaveService,
        private router: Router,
        private confirmationService: ConfirmationService
    ) { 

    }

    ngOnInit() {
        this.subscriptions.push(this.activatedRoute.params
            .subscribe(
                (params: Params) => {
                    this.showLoader = true;
                    if (params.id && params.id !== '0') {
                        this.showLoader = false;
                        this.getApplicate(params.id);
                    }
                }
            ));
    }

    deleteCV(application: any) {
        const isMandatory = application.Job.WorkFlowTemplate.IsCVMandatory;
        this.deleteConfirmation(application, isMandatory, 'CV');
    }

    deleteCoverLetter(application: any) {
        const isMandatory = application.Job.WorkFlowTemplate.IsCLMandatory;
        this.deleteConfirmation(application, isMandatory, 'CoverLetter');
    }

    deleteConfirmation(application: any, isMandatory: boolean, type: string) {
        this.confirmationService.confirm({
            message: isMandatory ? type + ' is mandatory in the Job Application. Do you want to proceed with the delete?' : 'Are you sure you want to delete this ' + type + '?',
            accept: () => {
                application.IsArchived = true;
                eval('application.' + type + ' = null');
            }
        });
    }

    onUpload(event: any, application: any, type: string) {
        eval('application.' + type + ' = { "FileToken": JSON.parse(event.xhr.response).files[0].token }');
        eval('application.' + type + 'Name = event.files[0]');
        this.showLoader = false;
    }

    getApplicate(id) {
        this.SearchApplicantService.getApplicantByID(id, ['User', 'JobApplications', 'JobApplications.Job.HiringTeam.Company', 'JobApplications.Job.WorkFlowTemplate']).subscribe(data => {
            this.applicant = data;
            this.showLoader = false;
        }, error => {
            this.utilsService.handleError(error);
            this.showLoader = false;
        })
    }

    saveApplicants(reload) {
        this.utilsService.clearErrorMessages();
        if (this.form.invalid) {
            this.utilsService.showAllErrorMessages();
        } else {
            this.showLoader = true;
            let updatedObjs = {};
            this.utilsService.addObjsToJSONByObjectID(updatedObjs, [this.applicant, this.applicant.User]);
            this.utilsService.addObjsToJSONByObjectID(updatedObjs, this.applicant.JobApplications);

            if (this.applicant.JobApplications) {
                for (let application of this.applicant.JobApplications) {
                    application.FactorScoreDetails = null;
                    application.CultureFit = null;
                    application.RoleFit = null;
                    application.RequirementFit = null;
                }
            }

            this.subscriptions.push(this.saveService.saveObjectsWithDefaultSvc({}, updatedObjs, {})
                .subscribe(
                    data => {
                        this.utilsService.handleSuccess();
                        if (reload) {
                            let idToNavigate = this.applicant.ObjectID;
                            this.getApplicate(idToNavigate);
                        }
                        else {
                            this.router.navigate(["/search-applicant"]);
                        }
                        this.showLoader = false;
                    },
                    error => {
                        this.showLoader = false;
                        this.utilsService.handleError(error);
                    }
                )
            );
        }
    }
}
