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

@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 = '';

    constructor(
        private as: AssessmentService,
        private hs: HelperService,
        private r: Router
    ) {
        super();
    }

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

    initiateDiversityProfile(): void {
        this.isLoading = true;
        this.as.getDiversityProfile(this.assocs)
            .pipe(takeUntil(this.componentInView))
            .subscribe(response => {
                this.isLoading = false;
                this.autoSavedOn = new Date();
                this.diversityProfiles = response;
                console.log(this.diversityProfiles);
            }, err => {
                this.isLoading = false;
                this.hs.handleHttpError(err);
            });
    }

    exit(): void {
        this.r.navigate(['/my-career-web/dashboard/home']);
    }

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

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

}
