import { Component, EventEmitter, OnInit, Output, ViewChild } from '@angular/core';
import { PersonalDetailsService } from '../../../services/personal-details.service';
import { CareerProfileModel } from '../../../models/career-profile.model';
import { UtilsService } from '../../../../oneit/services/utils.service';
import { ConfirmationService } from 'primeng/api';
import { NgForm } from '@angular/forms';
import { BaseComponent } from '../../../base/base.component';
import { takeUntil } from 'rxjs/operators';
import { EducationModel } from '../../../models/education.model';
import { environment } from '../../../../../environments/environment';

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

    assocs = ['EducationCertificates'];
    careerProfile = new CareerProfileModel();
    apiUrl = environment.baseUrl;
    uploadingFile = false;
    certifications = [];

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

    constructor(
        private personalDetailsService: PersonalDetailsService,
        private utilsService: UtilsService,
        private confirmationService: ConfirmationService
    ) {
        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;
                if (this.careerProfile.EducationCertificates) {
                    this.careerProfile.EducationCertificates.forEach(edu => {
                        edu.WhenCompletedField = UtilsService.convertStringToDate(edu.WhenCompleted);
                    })
                }
                this.utilsService.addObjsToJSONByObjectID(this.updatedObjs, this.careerProfile.EducationCertificates);
                this.addEducation(true);
                this.isLoading = false;
            }, err => {
                this.utilsService.handleError(err);
                this.isLoading = false;
            })
    }

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

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

    saveEducation(): void {
        if (this.form.invalid) {
            this.utilsService.showAllErrorMessages();
        }
        this.careerProfile.EducationCertificates.forEach(exp => {
            exp.WhenCompleted = UtilsService.convertDateToString(exp.WhenCompletedField);
        });
        this.isSaving = true;
        this.personalDetailsService.saveProfile(this.createdObjs, this.updatedObjs, this.deletedObjs)
            .pipe(takeUntil(this.componentInView))
            .subscribe(res => {
                this.isSaving = false;
                this.utilsService.handleError(res);
                this.educationSaved.emit();
            }, err => {
                this.utilsService.handleError(err);
                this.isSaving = false;
            })
    }

    getCertificates($event): void {
        this.personalDetailsService.getCertifications({CertificateName: $event.query})
            .pipe(takeUntil(this.componentInView))
            .subscribe(response => {
                this.certifications = response;
            }, err => {
                this.utilsService.handleError(err);
            })
    }

    uploadStarted(): void {
        this.uploadingFile = true;
    }

    onUpload($event, education: EducationModel): void {
        const response = JSON.parse($event.xhr.response);
        education.Certificate = {
            FileToken: response.files[0].token,
            Name: response.files[0].fileName,
        };
        this.uploadingFile = false;
    }

    removeAttachment(education: EducationModel): void {
        delete education.Certificate;
    }

}
