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 { CertificationModel, EducationModel } from '../../../models/education.model';
import { environment } from '../../../../../environments/environment';
import { Router } from '@angular/router';
import { HelperService } from '../../../services/helper.service';

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

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

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

    constructor(
        private personalDetailsService: PersonalDetailsService,
        private confirmationService: ConfirmationService,
        private utilsService: UtilsService,
        private helperService: HelperService,
        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;
                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(customRoute = null): void {
        if (this.form.invalid) {
            return this.helperService.validateAllFormFields(this.form);
        }
        this.careerProfile.EducationCertificates.forEach(exp => {
            if (typeof exp.Certification === 'string') {
                const certificate = new CertificationModel();
                certificate.CertificateName = exp.Certification;
                this.utilsService.createObject(certificate, this.createdObjs);
                exp.Certification = certificate;
            }
            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;
                if (customRoute) {
                    this.router.navigate([customRoute])
                } else {
                    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;
    }

}
