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

@Component({
    selector: 'app-work-style',
    templateUrl: './work-style.component.html',
    styleUrls: ['./work-style.component.scss']
})
export class WorkStyleComponent extends BaseComponent implements OnInit, OnDestroy {

    workStyleQuestion = new WorkStyleQuestionModel();
    assocs = ['Question', 'SelectedQuestion'];
    answerScales = [];
    autoSaveInterval;
    autoSavedOn;
    autoSaveLabel = 'a few seconds ago';
    wasUpdated = false;
    selectedAns;

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

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

    initiateWorkStyle(previousQuestion = false): void {
        this.isLoading = true;
        this.assessmentService.getWorkStyle(this.assocs, previousQuestion)
            .pipe(takeUntil(this.componentInView))
            .subscribe(response => {
                this.isLoading = false;
                this.autoSavedOn = new Date();
                this.autoSave();
                if (response.length > 0) {
                    this.workStyleQuestion = response[0];
                    this.selectedAns = this.workStyleQuestion.Answer ? this.workStyleQuestion.Answer : null;
                } else {
                    this.exit();
                }
                this.setAnswerScales();
            }, err => {
                this.isLoading = false;
                this.utilService.handleError(err);
                this.exit();
            });
    }

    setAnswerScales(): void {
        this.answerScales = [];
        setTimeout(() => {
            for (let i = 1; i <= (this.workStyleQuestion.Scalar || 1); i++) {
                this.answerScales.push(i);
            }
        });
    }

    submitAnswer(scale): void {
        this.selectedAns = scale;
        const formData = {
            Question: this.workStyleQuestion.Question.ObjectID,
            Answer: scale,
            Continue: true
        };
        this.isLoading = true;
        this.assessmentService.saveWorkStyle(formData)
            .subscribe(response => {
                this.selectedAns = null;
                this.isLoading = false;
                this.autoSavedOn = new Date();
                this.autoSave();
                this.wasUpdated = true;
                if (response.NextQuestion) {
                    this.workStyleQuestion = response.NextQuestion;
                    this.setAnswerScales();
                } else {
                    this.exit();
                }
            }, err => {
                this.isLoading = false;
                this.utilService.handleError(err);
            });
    }

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

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

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

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

}
