import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { RouterExtensions } from '@nativescript/angular';
import { SwipeDirection, SwipeGestureEventData } from '@nativescript/core/ui/gestures';
import { Select } from '@ngxs/store';
import { Observable } from 'rxjs';
import { AuthGuard } from '~/core/services/auth-guard.service';
import { EvaluationSurvey } from '../../entities/evaluation-survey';
import { EvaluationAnswerAllOutput } from '../../entities/output/evaluationAnswersOutput';
import { AnswersState } from '../../state-mgmt/evaluation-answers.state';
import { UpdateIndivEvaluationState } from '../../state-mgmt/evaluation-person-update.state';

@Component({
    selector: 'EvaluationDetailAnswers',
    moduleId: module.id,
    templateUrl: './evaluation-detail-answers.component.html',
    styleUrls: ['./evaluation-detail-answers.component.scss']
})

export class EvaluationDetailAnswersComponent implements OnInit {

    @Select(AnswersState.getAnswers) answers$: Observable<EvaluationAnswerAllOutput[]>;
    @Select(AnswersState.isLoading) answersIsLoading$: Observable<boolean>;
    @Select(AnswersState.getIDEval) idEval$: Observable<number>;

    @Select(UpdateIndivEvaluationState.isLoading) updateIsLoading$: Observable<boolean>;

    @ViewChild('scroller', {static: false}) scrollView: ElementRef;

    survey: EvaluationSurvey;
    checkProp: boolean = true;
    error: String = '';

    constructor(
        private routerExtensions: RouterExtensions,
        private authGuard: AuthGuard
    ) {}

    ngOnInit(): void {
        // We don't have to wait, because answeres are already loaded
        // Small timeout is set to load css styling of survey properly
        setTimeout(() => {
            this.answers$.subscribe(answersInput => this.survey = new EvaluationSurvey(answersInput));
        }, 10);
    }

    // Load previous page of survey
    onPrevPage(): void {
        this.authGuard.canActivate();
        this.survey.prevSet();
        this.pageChanged();
    }

    // Load next page of survey
    onNextPage(): void {
        this.authGuard.canActivate();
        this.survey.nextSet();
        this.pageChanged();
    }

    // back button action
    onBackButton(): void {
        this.routerExtensions.back();
    }

    // Swipe event - same as buttons: left swipe loads next page, right swipe loads previous page
    onSwipe(args: SwipeGestureEventData): void {
        if (args.direction === SwipeDirection.left && !this.survey.isLastPage()) {
            this.onNextPage();
        }
        if (args.direction === SwipeDirection.right && !this.survey.isFirstPage()) {
            this.onPrevPage();
        }
    }

    // Scroll to top on page change
    pageChanged(): void {
        const view = this.scrollView.nativeElement;
        view.scrollToVerticalOffset(0, false);
    }
}
