import { Component, OnDestroy, OnInit } from '@angular/core';
import { BaseComponent } from '../../base/base.component';
import * as moment from 'moment';
import { WorkPreferenceQuestionModel } from '../../models/work-preference-question.model';
import { takeUntil } from 'rxjs/operators';
import { AssessmentService } from '../../services/assessment.service';
import { Router } from '@angular/router';
import { QuestionModel } from '../../models/question.model';
import { UtilsService } from '../../../oneit/services/utils.service';
import { ToasterService } from '../../services/toaster.service';

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

export class WorkPreferenceComponent extends BaseComponent implements OnInit, OnDestroy {

    workPreferenceQuestion = new WorkPreferenceQuestionModel();
    assocs = ['CultureElement', 'CultureElement.Questions', 'SelectedQuestion'];
    wasUpdated = false;
    autoSaveInterval;
    autoSavedOn;
    autoSaveLabel = 'a few seconds ago';
    selectedAns;
    isBack;

    constructor(
        private assessmentService: AssessmentService,
        private utilService: UtilsService,
        private toasterService: ToasterService,
        private router: Router
    ) {
        super();
    }

    ngOnInit() {
        this.initiateWorkPreference();
        this.setAutoSaveInterval();
    }

    initiateWorkPreference(previousQuestion = false): void {
        this.isBack = previousQuestion;
        this.isLoading = true;
        this.assessmentService.getWorkPreferences(this.assocs, previousQuestion)
            .pipe(takeUntil(this.componentInView))
            .subscribe(response => {
                this.isLoading = false;
                this.autoSavedOn = new Date();
                this.autoSave();
                this.wasUpdated = true;
                if (response.length > 0) {
                    this.workPreferenceQuestion = response[0];
                    if (this.workPreferenceQuestion.SelectedQuestion) {
                        this.selectedAns = this.workPreferenceQuestion.SelectedQuestion.ObjectID;
                    }
                } else {
                    this.exit();
                }
            }, err => {
                this.isLoading = false;
                this.utilService.handleError(err);
            });
    }

    setAutoSaveInterval(): void {
        if (!this.autoSaveInterval) {
            setInterval(() => {
                this.autoSave();
            }, 60000);
        }
    }

    autoSave(): void {
        this.autoSaveLabel = moment(this.autoSavedOn).fromNow();
    }

    exit(): void {
        if (this.wasUpdated) {
            this.toasterService.success('Preferences updated!');
        }
        this.router.navigate(['/my-career-web/dashboard/home']);
    }

    submitAnswer(question: QuestionModel): void {
        this.selectedAns = question.ObjectID;
        const formData = {
            CultureElement: this.workPreferenceQuestion.CultureElement.ObjectID,
            SelectedQuestion: question.ObjectID,
            Continue: true
        };
        this.isLoading = true;
        this.assessmentService.saveWorkPreferences(formData)
            .subscribe(response => {
                this.selectedAns = null;
                this.isLoading = false;
                this.autoSavedOn = new Date();
                this.autoSave();
                if (response.NextQuestion) {
                    this.initiateWorkPreference();
                } else {
                    this.exit();
                }
            }, err => {
                this.isLoading = false;
                this.utilService.handleError(err);
            });
    }

    ngOnDestroy(): void {
        super.ngOnDestroy();
        if (this.autoSaveInterval) {
            clearInterval(this.autoSaveInterval);
        }
    }

}
