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 { HelperService } from '../../../services/helper.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';

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

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

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

    constructor(
        private ps: PersonalDetailsService,
        private us: UtilsService,
        private cs: ConfirmationService,
        private hs: HelperService
    ) {
        super();
    }

    ngOnInit() {
        this.getCareerProfile();
    }

    getCareerProfile(): void {
        this.isLoading = true;
        this.ps.getCareerProfile(this.assocs)
            .pipe(takeUntil(this.componentInView))
            .subscribe(response => {
                this.isLoading = false;
                this.careerProfile = response;
                if (this.careerProfile.WorkExperiences) {
                    this.careerProfile.WorkExperiences.forEach(exp => {
                        exp.StartMonthField = UtilsService.convertStringToDate(exp.StartMonth);
                        exp.EndMonthField = UtilsService.convertStringToDate(exp.EndMonth);
                    })
                }
                this.us.addObjsToJSONByObjectID(this.updatedObjs, this.careerProfile.WorkExperiences);
                this.addWorkExperience(true);
            }, err => {
                this.hs.handleHttpError(err);
                this.isLoading = false;
            })
    }

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

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

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

    saveWorkHistory(): void {
        this.hs.validateAllFormFields(this.form);
        if (this.form.invalid) {
            return ;
        }
        this.careerProfile.WorkExperiences.forEach(exp => {
            exp.StartMonth = UtilsService.convertDateToString(exp.StartMonthField);
            exp.EndMonth = UtilsService.convertDateToString(exp.EndMonthField);
        });
        this.isSaving = true;
        this.ps.saveProfile(this.createdObjs, this.updatedObjs, this.deletedObjs)
            .pipe(takeUntil(this.componentInView))
            .subscribe(res => {
                this.isSaving = false;
                this.hs.oneItHttpResponse(res);
                this.workSaved.emit();
            }, err => {
                this.hs.handleHttpError(err);
                this.isSaving = false;
            })
    }

}
