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';

@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 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;
                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(): void {
        if (this.form.invalid) {
            return this.utilsService.clearErrorMessages();
        }
        this.isSaving = true;
        this.personalDetailsService.saveProfile(this.createdObjs, this.updatedObjs, this.deletedObjs)
            .pipe(takeUntil(this.componentInView))
            .subscribe(res => {
                this.isSaving = false;
                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;
    }


}
