import { Component, OnInit, ViewChild } from '@angular/core';
import { BaseComponent } from '../../base/base.component';
import { IntroductionLetterModel } from '../../models/introduction-letter.model';
import { ActivatedRoute, Router } from '@angular/router';
import { takeUntil } from 'rxjs/operators';
import { UtilsService } from '../../../oneit/services/utils.service';
import { PersonalDetailsService } from '../../services/personal-details.service';
import { CareerProfileModel } from '../../models/career-profile.model';
import { IntroLetterService } from '../../services/intro-letter.service';
import { NgForm } from '@angular/forms';
import { HelperService } from '../../services/helper.service';
import { ILWorkExperienceModel } from '../../models/il-work-experience.model';
import { ILSkillModel } from '../../models/il-skill.model';

import * as FileSaver from 'file-saver';
import { ToasterService } from '../../services/toaster.service';

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

    introLetterId;
    introductionLetter = new IntroductionLetterModel();
    careerProfile = new CareerProfileModel();
    isLoadingSkillAndExp = false;

    @ViewChild('form') form: NgForm;

    constructor(
        private activatedRoute: ActivatedRoute,
        private personalDetailsService: PersonalDetailsService,
        private introLetterService: IntroLetterService,
        private utilsService: UtilsService,
        private helperService: HelperService,
        private toastService: ToasterService,
        private router: Router
    ) {
        super();
    }

    ngOnInit() {
        this.activatedRoute.params
            .pipe(takeUntil(this.componentInView))
            .subscribe(params => {
                if (params.id && params.id !== 'new') {
                    this.isEditMode = true;
                    this.introLetterId = params.id;
                    this.getIntroLetter()
                }
            });
        this.getCareerProfile();
    }

    getCareerProfile(): void {
        this.isLoadingSkillAndExp = true;
        const assocs = ['WorkExperiences', 'WorkExperiences', 'Skills.Skill'];
        this.personalDetailsService.getCareerProfile(assocs)
            .pipe(takeUntil(this.componentInView))
            .subscribe(response => {
                this.isLoadingSkillAndExp = false;
                this.careerProfile = response;
                if (!this.isEditMode) {
                    this.introductionLetter = new IntroductionLetterModel();
                    this.introductionLetter.Candidate = this.careerProfile.Candidate;
                    this.utilsService.createObject(this.introductionLetter, this.createdObjs);
                    this.initialProcessing();
                }
            }, err => {
                this.isLoadingSkillAndExp = false;
                this.utilsService.handleError(err);
            })
    }

    getIntroLetter(download = false): void {
        this.isLoading = true;
        const sub = download ? this.introLetterService.downloadIntroLetter(this.introLetterId) : this.introLetterService.getIntroLetter(this.introLetterId, ['WorkExperiences.WorkExperience', 'Skills.Skill']);
        sub
            .pipe(takeUntil(this.componentInView))
            .subscribe(response => {
                this.isLoading = false;
                if (download) {
                    FileSaver.saveAs(response.content, `intro-letter-${this.introductionLetter.ObjectID}.pdf`);
                } else {
                    this.introductionLetter = response;
                    this.updatedObjs[this.introductionLetter.ObjectID] = this.introductionLetter;
                }
            }, err => {
                this.utilsService.handleError(err);
                this.isLoading = false;
            })
    }

    initialProcessing(): void {
        this.careerProfile.WorkExperiences.forEach((w, i) => {
            const ilWorkExperience = new ILWorkExperienceModel();
            ilWorkExperience.IntroductionLetter = this.introductionLetter.ObjectID;
            ilWorkExperience.WorkExperience = w;
            ilWorkExperience.SortOrder = i;
            ilWorkExperience.IsSelected = true;
            this.utilsService.addMultiRefObject(ilWorkExperience, this.introductionLetter, 'WorkExperiences', this.createdObjs);
        });
        this.careerProfile.Skills.forEach((s, i) => {
            const ilSkillModel = new ILSkillModel();
            ilSkillModel.IntroductionLetter = this.introductionLetter.ObjectID;
            ilSkillModel.Skill = s.Skill;
            ilSkillModel.SortOrder = i;
            ilSkillModel.IsSelected = true;
            this.utilsService.addMultiRefObject(ilSkillModel, this.introductionLetter, 'Skills', this.createdObjs);
        });
    }

    saveIntroLetter(): void {
        if (this.form.invalid) {
            return this.helperService.validateAllFormFields(this.form);
        }
        if (this.introductionLetter.WorkExperiences) {
            this.introductionLetter.WorkExperiences.forEach((w, i) => {
                w.SortOrder = i;
            });
        }
        if (this.introductionLetter.Skills) {
            this.introductionLetter.Skills.forEach((s, i) => {
                s.SortOrder = i;
            });
        }
        this.isLoading = true;
        this.introLetterService.saveIntroLetters(this.createdObjs, this.updatedObjs, this.deletedObjs)
            .pipe(takeUntil(this.componentInView))
            .subscribe(() => {
                this.isLoading = false;
                this.toastService.success('Intro letter saved');
                this.router.navigate([`my-career-web/intro-letters`])
            }, err => {
                this.utilsService.handleError(err);
                this.isLoading = false;
            });
    }

}
