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

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

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

    @ViewChild('form') form: NgForm;
    @Output() educationSaved = new EventEmitter();
    @Output() careerProfileLoaded = new EventEmitter<CareerProfileModel>();

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

    ngOnInit() {
        this.getCareerProfile();
        this.personalDetailsService.getStudied()
            .pipe(takeUntil(this.componentInView))
            .subscribe(response => {
                this.studied = response.filter(s => !!s);
            }, err => {
                this.utilsService.handleError(err);
            });
    }

    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);
                if ((!this.careerProfile.EducationCertificates || this.careerProfile.EducationCertificates.length === 0) && !this.careerProfile.NoEducationQualification) {
                    for (let i = 0; i < this.careerProfile.NoOfQualifications || 0; i++) {
                        this.addEducation(true);
                    }
                }
                this.careerProfileLoaded.emit(this.careerProfile);
            }, err => {
                this.utilsService.handleError(err);
                this.isLoading = false;
            })
    }

    suggestedStudiedAt($event): void {
        setTimeout(() => {
            this.filterStudied = $event.query ? this.studied.filter(s => s.startsWith($event.query)) : this.studied.slice();
        });
    }

    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.saveProfileDefault(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;
    }

}
