import { Component, EventEmitter, Input, OnInit, Output } 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 { BaseComponent } from '../../../base/base.component';
import { takeUntil } from 'rxjs/operators';
import { ToasterService } from '../../../services/toaster.service';
import { Router } from '@angular/router';
import { CAREER_TABS } from '../../../config/constants';

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

    assocs = [];
    careerProfile = new CareerProfileModel();
    @Input() asChild = false;
    @Output() careerProfileLoaded = new EventEmitter<CareerProfileModel>();

    constructor(
        private personalDetailsService: PersonalDetailsService,
        private toasterService: ToasterService,
        private router: Router,
        private utilsService: UtilsService
    ) {
        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.careerProfileLoaded.emit(this.careerProfile);
            }, err => {
                this.isLoading = false;
                this.utilsService.handleError(err);
            })
    }

    saveProfile(complete = false): void {
        this.isSaving = true;
        this.careerProfile.CurrentProfileBuilderTab = CAREER_TABS.PUBLISH;
        this.personalDetailsService.saveProfileDefault(this.createdObjs, this.updatedObjs, this.deletedObjs)
            .pipe(takeUntil(this.componentInView))
            .subscribe(res => {
                this.isSaving = false;
                if (complete) {
                    this.toasterService.success('You have completed you career history, one step closer to done.');
                    this.router.navigate(['/my-career-web/dashboard/home']);
                } else {
                    this.getCareerProfile();
                }
            }, err => {
                this.isLoading = false;
                this.utilsService.handleError(err);
            })
    }

}
