import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { Router } from '@angular/router';
import { takeUntil } from 'rxjs/operators';
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 { PersonalDetailsService } from '../../../services/personal-details.service';
import { ToasterService } from '../../../services/toaster.service';

@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);
            })
    }

    get isComplete(): boolean {
        return this.careerProfile.ProfileBulderTabCompletion && Object.keys(this.careerProfile.ProfileBulderTabCompletion)
            .every(key => this.careerProfile.ProfileBulderTabCompletion[key]);
    }

    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 your 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);
            })
    }

}
