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

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

    diversityProfiles: DiversityProfileQuestionModel[] = [];
    assocs = ['Answers'];
    autoSaveInterval;
    autoSavedOn;
    autoSaveLabel = 'a few seconds ago';
    selectedAnswers = [];

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

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

    initiateDiversityProfile(): void {
        this.isLoading = true;
        this.assessmentService.getDiversityProfile(this.assocs)
            .pipe(takeUntil(this.componentInView))
            .subscribe(response => {
                this.isLoading = false;
                this.autoSavedOn = new Date();
                this.diversityProfiles = response;
                this.setAnswers();
            }, err => {
                this.isLoading = false;
                this.utilsService.handleError(err);
            });
    }

    setAnswers(): void {
        this.diversityProfiles.forEach(div => {
            if (!div.MultipleAnswers) {
                this.selectedAnswers[div.ObjectID] = div.Answers.find(a => a.IsSelected);
            } else {
                this.selectedAnswers[div.ObjectID] = div.Answers.filter(a => a.IsSelected).map(a => a.ObjectID);
            }
        });
    }

    exit(): void {
        this.isSaving = true;
        const answers = [];
        this.diversityProfiles.forEach(div => {
            if (div.MultipleAnswers) {
                answers.push(...this.selectedAnswers[div.ObjectID]);
            } else {
                answers.push(this.selectedAnswers[div.ObjectID])
            }
        });
        this.assessmentService.saveDiversityProfile({Answers: answers})
            .pipe(takeUntil(this.componentInView))
            .subscribe(() => {
                this.isSaving = false;
                this.toasterService.success('Diversity profile updated!');
                this.router.navigate(['/my-career-web/dashboard/home']);
            }, err => {
                this.isSaving = false;
                this.utilsService.handleError(err);
            });
    }

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

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

}
