import { Component, OnInit, ViewChild } from '@angular/core';
import { BaseComponent } from '../../../base/base.component';
import { ApplicantJobModel } from '../../../models/applicant-job.model';
import { JobService } from '../../../services/job.service';
import { takeUntil } from 'rxjs/operators';
import { UtilsService } from '../../../../oneit/services/utils.service';
import { ActivatedRoute, Router } from '@angular/router';
import { NgForm } from '@angular/forms';
import { HelperService } from '../../../services/helper.service';
import { ToasterService } from '../../../services/toaster.service';
import { PersonalDetailsService } from '../../../services/personal-details.service';
import { CareerProfileModel } from '../../../models/career-profile.model';

@Component({
    selector: 'app-job',
    templateUrl: './job-details.component.html',
    styleUrls: ['./job-details.component.scss']
})
export class JobDetailsComponent extends BaseComponent implements OnInit {

    applicantJob: ApplicantJobModel = new ApplicantJobModel();
    clonedCareerProfile: CareerProfileModel = new CareerProfileModel();
    applicantJobId;

    isLoadingJobLocations = false;
    jobPostLocations = [];

    detailStep = 1;
    selectedProfileType: 'same' | 'customize' = 'same';

    @ViewChild('form') form: NgForm;

    constructor(
        private activatedRoute: ActivatedRoute,
        private jobService: JobService,
        private utilsService: UtilsService,
        private toastService: ToasterService,
        private helperService: HelperService,
        private personalDetailsService: PersonalDetailsService,
        private router: Router
    ) {
        super();
    }

    ngOnInit() {
        this.activatedRoute.params
            .pipe(takeUntil(this.componentInView))
            .subscribe(params => {
                if (params.id && params.id !== 'new') {
                    this.isEditMode = true;
                    this.applicantJobId = params.id;
                }
            });
        this.getCloneCareerProfileID();
        this.getJobPostLocations();
    }

    getCloneCareerProfileID(): void {
        this.isLoading = true;
        this.personalDetailsService.getCloneCareerProfile()
            .pipe(takeUntil(this.componentInView))
            .subscribe(cloneProfileID => {
                this.getCareerProfile(cloneProfileID);
            }, err => {
                this.isLoading = false;
                this.utilsService.handleError(err);
            });
    }

    getCareerProfile(id): void {
        this.personalDetailsService.getCareerProfileById(id, [])
            .pipe(takeUntil(this.componentInView))
            .subscribe(response => {
                this.isLoading = false;
                this.clonedCareerProfile = response;
                this.initiateApplicantJob();
            }, err => {
                this.isLoading = false;
                this.utilsService.handleError(err);
            });
    }

    initiateApplicantJob(): void {
        if (this.isEditMode) {
            this.getApplicantJob()
        } else {
            this.applicantJob = new ApplicantJobModel();
            this.applicantJob.Candidate = this.clonedCareerProfile.Candidate;
            this.utilsService.createObject(this.applicantJob, this.createdObjs)
        }
    }

    getApplicantJob(): void {
        this.isLoading = true;
        this.jobService.getApplicantJob(this.applicantJobId)
            .pipe(takeUntil(this.componentInView))
            .subscribe(response => {
                this.isLoading = false;
                this.applicantJob = response;
                this.updatedObjs[this.applicantJob.ObjectID] = this.applicantJob;
            }, err => {
                this.utilsService.handleError(err);
                this.isLoading = false;
            })
    }

    getJobPostLocations(): void {
        this.isLoadingJobLocations = true;
        this.jobService.getJobPostedLocation()
            .pipe(takeUntil(this.componentInView))
            .subscribe(response => {
                this.isLoadingJobLocations = false;
                this.jobPostLocations = response;
            }, err => {
                this.isLoadingJobLocations = false;
                this.utilsService.handleError(err);
            })
    }

    selectProfile(): void {
        if (this.form.invalid) {
            return this.helperService.validateAllFormFields(this.form);
        }
        if (!this.isEditMode) {
            this.detailStep = 2;
        } else {
            this.saveApplicantJob();
        }
    }

    saveApplicantJob(exit = false): void {
        this.isLoading = true;
        this.jobService.saveApplicantJob(this.createdObjs, this.updatedObjs, this.deletedObjs)
            .pipe(takeUntil(this.componentInView))
            .subscribe(() => {
                this.isLoading = false;
                this.toastService.success(this.isEditMode ? 'Job updated.' : 'Job saved.');
                if (exit) {
                    this.router.navigate([`my-career-web/jobs`]);
                } else {
                    if (this.selectedProfileType === 'customize' || this.isEditMode) {
                        console.log('REDIRECT PERSONAL');
                    } else if (this.selectedProfileType === 'same') {
                        console.log('REDIRECT TO LETTER');
                    }
                }
            }, err => {
                this.utilsService.handleError(err);
                this.isLoading = false;
            });
    }

}
