import { Component, EventEmitter, OnInit, Output, ViewChild } from '@angular/core';
import { BaseComponent } from '../../../base/base.component';
import { takeUntil } from 'rxjs/operators';
import { CareerProfileModel } from '../../../models/career-profile.model';
import { PersonalDetailsService } from '../../../services/personal-details.service';
import { UtilsService } from '../../../../oneit/services/utils.service';
import { WorkExperienceModel } from '../../../models/work-experience.model';
import { NgForm } from '@angular/forms';
import { ConfirmationService } from 'primeng/api';
import { Router } from '@angular/router';
import { HelperService } from '../../../services/helper.service';
import { ToasterService } from '../../../services/toaster.service';
import { CAREER_TABS } from '../../../config/constants';

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

    assocs = ['WorkExperiences', 'WorkExperiences.ILOJobTitle'];
    careerProfile = new CareerProfileModel();
    jobTitles = [];
    employers = [];

    @ViewChild('form') form: NgForm;
    @Output() workSaved = new EventEmitter();

    constructor(
        private personalDetailsService: PersonalDetailsService,
        private confirmationService: ConfirmationService,
        private utilsService: UtilsService,
        private helperService: HelperService,
        private toastService: ToasterService,
        private router: Router
    ) {
        super();
    }

    ngOnInit() {
        this.getCareerProfile();
    }

    getCareerProfile(): void {
        this.isLoading = true;
        this.personalDetailsService.getCareerProfile(this.assocs)
            .pipe(takeUntil(this.componentInView))
            .subscribe(response => {
                this.isLoading = false;
                this.careerProfile = response;
                this.updatedObjs[this.careerProfile.ObjectID] = this.careerProfile;
                if (this.careerProfile.WorkExperiences) {
                    this.careerProfile.WorkExperiences.forEach(exp => {
                        exp.StartMonthField = UtilsService.convertStringToDate(exp.StartMonth);
                        exp.EndMonthField = UtilsService.convertStringToDate(exp.EndMonth);
                    })
                }
                this.utilsService.addObjsToJSONByObjectID(this.updatedObjs, this.careerProfile.WorkExperiences);
                this.addWorkExperience(true);
            }, err => {
                this.isLoading = false;
                this.utilsService.handleError(err);
            })
    }

    suggestedEmployer($event): void {
        this.personalDetailsService.getEmployers({Details: $event.query})
            .pipe(takeUntil(this.componentInView))
            .subscribe(response => {
                this.employers = response;
            }, err => {
                this.utilsService.handleError(err);
            });
    }

    addWorkExperience(initLoad = false): void {
        const newModel = new WorkExperienceModel();
        newModel.CareerProfile = this.careerProfile.ObjectID;
        if (initLoad && (!this.careerProfile.WorkExperiences || this.careerProfile.WorkExperiences.length === 0)) {
            this.utilsService.addMultiRefObject(newModel, this.careerProfile, 'WorkExperiences', this.createdObjs);
        } else if (!initLoad) {
            this.utilsService.addMultiRefObject(newModel, this.careerProfile, 'WorkExperiences', this.createdObjs);
        }
    }

    getJobTitles($event): void {
        this.personalDetailsService.getJobTitles({JobTitle: $event.query})
            .pipe(takeUntil(this.componentInView))
            .subscribe(response => {
                this.jobTitles = response.filter(r => r.JobTitle);
            }, err => {
                this.utilsService.handleError(err);
            })
    }

    removeExperience(exp): void {
        this.confirmationService.confirm({
            message:'Are you sure you want to remove this experience?',
            accept: () => {
                this.utilsService.removeMultiRefObject(exp, this.careerProfile, 'WorkExperiences', this.createdObjs, this.updatedObjs, this.deletedObjs);
            }
        })
    }

    saveWorkHistory(customRoute = null): void {
        if (this.form.invalid) {
            return this.helperService.validateAllFormFields(this.form);
        }
        if (this.careerProfile.NoWorkExperience) {
            while (this.careerProfile.WorkExperiences.length > 0) {
                this.utilsService.removeMultiRefObject(this.careerProfile.WorkExperiences[0], this.careerProfile, 'WorkExperiences', this.createdObjs, this.updatedObjs, this.deletedObjs);
            }
        }
        this.careerProfile.WorkExperiences.forEach(exp => {
            exp.StartMonth = UtilsService.convertDateToString(exp.StartMonthField);
            exp.EndMonth = UtilsService.convertDateToString(exp.EndMonthField);
        });
        this.isSaving = true;
        if (this.careerProfile.CompletedPercentageCH <= 40) {
            this.careerProfile.CurrentProfileBuilderTab = CAREER_TABS.EDUCATION;
        }
        this.personalDetailsService.saveProfileDefault(this.createdObjs, this.updatedObjs, this.deletedObjs)
            .pipe(takeUntil(this.componentInView))
            .subscribe(res => {
                this.isSaving = false;
                this.toastService.success('Work history updated');
                if (customRoute) {
                    this.router.navigate([customRoute])
                } else {
                    this.workSaved.emit();
                }
            }, err => {
                this.utilsService.handleError(err);
                this.isSaving = false;
            })
    }

}
