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';
import { CAREER_TABS } from '../../../config/constants';

@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;
                this.updatedObjs[this.careerProfile.ObjectID] = this.careerProfile;
                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);
        }
        if (this.careerProfile.NoEducationQualification) {
            while (this.careerProfile.EducationCertificates.length > 0) {
                this.utilsService.removeMultiRefObject(this.careerProfile.EducationCertificates[0], this.careerProfile, 'EducationCertificates', this.createdObjs, this.updatedObjs, this.deletedObjs);
            }
        }
        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;
        if (this.careerProfile.CompletedPercentageCH <= 60) {
            this.careerProfile.CurrentProfileBuilderTab = CAREER_TABS.SKILLS;
        }
        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;
    }

}
