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

@Component({
    selector: 'app-job',
    templateUrl: './job-details.component.html',
    styleUrls: ['./job-details.component.scss']
})
export class JobDetailsComponent extends JobBaseComponent 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(
        activatedRoute: ActivatedRoute,
        jobService: JobService,
        utilsService: UtilsService,
        private toastService: ToasterService,
        private helperService: HelperService,
        private personalDetailsService: PersonalDetailsService,
        private router: Router
    ) {
        super(activatedRoute, jobService, utilsService);
    }

    ngOnInit() {
        this.activatedRoute.params
            .pipe(takeUntil(this.componentInView))
            .subscribe(params => {
                if (params.id && params.id !== 'new') {
                    this.isEditMode = true;
                    this.applicantJobId = params.id;
                    this.getApplicantJob();
                } else {
                    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 {
        this.applicantJob = new ApplicantJobModel();
        this.applicantJob.Candidate = this.clonedCareerProfile.Candidate;
        this.applicantJob.CareerProfile = this.clonedCareerProfile.ObjectID;
        this.utilsService.createObject(this.applicantJob, this.createdObjs)
    }

    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();
        }
    }

    jobLoaded(): void {
        // console.log(this.applicantJob);
    }

    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) {
                        this.router.navigate([`/my-career-web/jobs/${this.applicantJobId}/personal-details`]);
                    } else if (this.selectedProfileType === 'same') {
                        console.log('REDIRECT TO LETTER');
                    }
                }
            }, err => {
                this.utilsService.handleError(err);
                this.isLoading = false;
            });
    }

}
