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 { HelperService } from '../../services/helper.service';
import { PersonalDetailsService } from '../../services/personal-details.service';
import { ToasterService } from '../../services/toaster.service';
import { Router } from '@angular/router';

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

    @ViewChild('form') form: NgForm;

    constructor(
        private ps: PersonalDetailsService,
        private ts: ToasterService,
        private hs: HelperService,
        private aps: AppService,
        private r: Router
    ) {
        super();
    }

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

    getEmploymentStatuses(): void {
        this.isLoadingStatuses = true;
        this.ps.getEmploymentStatuses()
            .pipe(takeUntil(this.componentInView))
            .subscribe(response => {
                this.employmentStatuses = response;
                this.isLoadingStatuses = false;
            }, err => {
                this.hs.handleHttpError(err);
                this.isLoadingStatuses = false;
            })
    }

    getEmploymentPreferences(): void {
        this.isLoadingPreferences = true;
        this.ps.getEmploymentPreferences()
            .pipe(takeUntil(this.componentInView))
            .subscribe(response => {
                this.employmentPreferences = response;
                this.isLoadingPreferences = false;
            }, err => {
                this.hs.handleHttpError(err);
                this.isLoadingPreferences = false;
            })
    }

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

    getCareerProfile(): void {
        this.isLoading = true;
        this.ps.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.ps.careerProfileUpdated = this.careerProfile;
                this.isLoading = false;
            }, err => {
                this.hs.handleHttpError(err);
                this.isLoading = false;
            })
    }

    updateProfile(): void {
        this.hs.validateAllFormFields(this.form);
        if (this.form.invalid) {
            return ;
        }
        this.careerProfile.Candidate.User.UserName = this.careerProfile.Candidate.User.Email;
        this.isSaving = true;
        this.ps.saveProfile(this.createdObjs, this.updatedObjs, this.deletedObjs)
            .pipe(takeUntil(this.componentInView))
            .subscribe(res => {
                this.isSaving = false;
                this.hs.oneItHttpResponse(res);
                this.ps.careerProfileUpdated = this.careerProfile;
                this.ts.success('Profile updated.');
                if (!this.asChildComponent) {
                    this.r.navigate(['/my-career-web/dashboard/home']);
                } else {
                    this.detailsSaved.emit();
                }
            }, err => {
                this.hs.handleHttpError(err);
                this.isSaving = false;
            })
    }

    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.aps.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.hs.handleHttpError(err);
                }
            )
    }

}
