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 { RefereeModel } from '../../../models/referee.model';
import { environment } from '../../../../../environments/environment';
import { Router } from '@angular/router';
import { HelperService } from '../../../services/helper.service';
import { ToasterService } from '../../../services/toaster.service';
import { CAREER_TABS } from '../../../config/constants';

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

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

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

    constructor(
        private personalDetailsService: PersonalDetailsService,
        private confirmationService: ConfirmationService,
        private utilsService: UtilsService,
        private helperService: HelperService,
        private toasterService: ToasterService,
        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;
                this.utilsService.addObjsToJSONByObjectID(this.updatedObjs, this.careerProfile.Referees);
                this.addReferee(true);
                this.isLoading = false;
            }, err => {
                this.isLoading = false;
                this.utilsService.handleError(err);
            })
    }

    checkMobilePattern(referee) {
        if (referee.Mobile && referee.Mobile.length < 11) {
            referee.Mobile = '';
        }
    }

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

    removeReferee(ref): void {
        this.confirmationService.confirm({
            message:'Are you sure you want to remove this skill?',
            accept: () => {
                this.utilsService.removeMultiRefObject(ref, this.careerProfile, 'Referees', this.createdObjs, this.updatedObjs, this.deletedObjs);
            }
        })
    }

    saveReferees(customRoute = null): void {
        if (this.form.invalid) {
            return this.helperService.validateAllFormFields(this.form);
        }
        if (this.careerProfile.NoReference) {
            while (this.careerProfile.Referees.length > 0) {
                this.utilsService.removeMultiRefObject(this.careerProfile.Referees[0], this.careerProfile, 'Referees', this.createdObjs, this.updatedObjs, this.deletedObjs);
            }
        }
        this.isSaving = true;
        if (this.careerProfile.CompletedPercentageCH <= 80) {
            this.careerProfile.CurrentProfileBuilderTab = CAREER_TABS.PUBLISH;
        }
        this.personalDetailsService.saveProfile(this.createdObjs, this.updatedObjs, this.deletedObjs)
            .pipe(takeUntil(this.componentInView))
            .subscribe(res => {
                this.toasterService.success('References updated');
                this.isSaving = false;
                if (customRoute) {
                    this.router.navigate([customRoute])
                } else {
                    this.refereeSaved.emit();
                }
            }, err => {
                this.isLoading = false;
                this.utilsService.handleError(err);
            })
    }

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

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

    removeAttachment(refree: RefereeModel): void {
        delete refree.WrittenReference;
    }


}
