import { Component, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { takeUntil } from 'rxjs/operators';
import { AppService } from '../../../app.service';
import { BaseComponent } from '../../base/base.component';
import { CareerProfileModel } from '../../models/career-profile.model';
import { PersonalDetailsService } from '../../services/personal-details.service';
import { ToasterService } from '../../services/toaster.service';
import { Router } from '@angular/router';
import { UtilsService } from '../../../oneit/services/utils.service';
import { HelperService } from '../../services/helper.service';
import { CAREER_TABS } from '../../config/constants';

@Component({
    selector: 'app-personal-details',
    templateUrl: './personal-details.component.html',
    styleUrls: ['./personal-details.component.scss']
})

export class PersonalDetailsComponent extends BaseComponent implements OnInit {

    isLoadingStatuses = false;
    isLoadingPreferences = false;
    employmentStatuses = [];
    employmentPreferences = [];
    jobTitles = [];
    careerProfile = new CareerProfileModel();
    assocs = ['Candidate.User', 'Candidate.OccupationPreference'];
    @Input() asChildComponent = false;
    @Output() detailsSaved = new EventEmitter();
    @Output() careerProfileLoaded = new EventEmitter<CareerProfileModel>();

    @ViewChild('form') form: NgForm;

    constructor(
        private personalDetailsService: PersonalDetailsService,
        private toasterService: ToasterService,
        private appService: AppService,
        private utilsService: UtilsService,
        private helperService: HelperService,
        private router: Router
    ) {
        super();
    }

    ngOnInit() {
        this.getEmploymentStatuses();
        this.getEmploymentPreferences();
        this.getCareerProfile();
    }

    getEmploymentStatuses(): void {
        this.isLoadingStatuses = true;
        this.personalDetailsService.getEmploymentStatuses()
            .pipe(takeUntil(this.componentInView))
            .subscribe(response => {
                this.employmentStatuses = response;
                this.isLoadingStatuses = false;
            }, err => {
                this.isLoadingStatuses = false;
                this.utilsService.handleError(err);
            })
    }

    getEmploymentPreferences(): void {
        this.isLoadingPreferences = true;
        this.personalDetailsService.getEmploymentPreferences()
            .pipe(takeUntil(this.componentInView))
            .subscribe(response => {
                this.employmentPreferences = response;
                this.isLoadingPreferences = false;
            }, err => {
                this.isLoadingPreferences = false;
                this.utilsService.handleError(err);
            })
    }

    getJobTitles($event): void {
        this.personalDetailsService.getJobTitles({JobTitle: $event.query})
            .pipe(takeUntil(this.componentInView))
            .subscribe(response => {
                this.jobTitles = response.filter(r => r.JobTitle);
            }, err => {
                this.utilsService.handleError(err);
            })
    }

    getCareerProfile(): void {
        this.isLoading = true;
        this.personalDetailsService.getCareerProfile(this.assocs)
            .pipe(takeUntil(this.componentInView))
            .subscribe(response => {
                this.careerProfile = response;
                this.updatedObjs[this.careerProfile.ObjectID] = this.careerProfile;
                this.updatedObjs[this.careerProfile.Candidate.ObjectID] = this.careerProfile.Candidate;
                this.updatedObjs[this.careerProfile.Candidate.User.ObjectID] = this.careerProfile.Candidate.User;
                if (this.careerProfile.Candidate.EmploymentPreference) {
                    this.careerProfile.Candidate.EmploymentPreference = this.careerProfile.Candidate.EmploymentPreference.map(p => p.Value);
                }
                this.personalDetailsService.careerProfileUpdated = this.careerProfile;
                this.careerProfileLoaded.emit(this.careerProfile);
                this.isLoading = false;
            }, err => {
                this.isLoading = false;
                this.utilsService.handleError(err);
            })
    }

    updateProfile(customRoute = null): void {
        if (this.form.invalid) {
            return this.helperService.validateAllFormFields(this.form);
        }
        this.careerProfile.Candidate.User.UserName = this.careerProfile.Candidate.User.Email;
        this.isSaving = true;
        if (this.careerProfile.CompletedPercentageCH <= 20) {
            this.careerProfile.CurrentProfileBuilderTab = CAREER_TABS.WORK_HISTORY;
        }
        this.personalDetailsService.saveProfile(this.createdObjs, this.updatedObjs, this.deletedObjs)
            .pipe(takeUntil(this.componentInView))
            .subscribe(res => {
                this.isSaving = false;
                this.personalDetailsService.careerProfileUpdated = this.careerProfile;
                this.toasterService.success('Profile updated.');
                if (!this.asChildComponent) {
                    this.router.navigate(['/my-career-web/dashboard/home']);
                } else {
                    if (customRoute) {
                        this.router.navigate([customRoute]);
                    } else {
                        this.detailsSaved.emit();
                    }
                }
            }, err => {
                this.isSaving = false;
                this.utilsService.handleError(err);
            })
    }

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

    changedAddress(): void {
        this.careerProfile.GoogleAddress = '';
    }

    updateAddress($event): void {
        this.careerProfile.GoogleAddress = $event.formatted;
    }

    connectWithSocial(type): void {
        this.isLoading = true;
        this.appService.socicalMediaLogin(type)
            .pipe(takeUntil(this.componentInView))
            .subscribe(data => {
                    this.isLoading = false;
                    if (data.destination) {
                        window.location.href = data.destination;
                        return;
                    }
                },
                err => {
                    this.isLoading = false;
                    this.utilsService.handleError(err);
                }
            )
    }

}
