import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { CommonModule } from '@angular/common';
import { Observable, Subscription } from 'rxjs';

import { Errors, QCM, User } from 'src/app/core/models';
import { QCMService, UserService } from 'src/app/core/services';

@Component({
    selector: 'huapp-qcm',
    standalone: true,
    imports: [CommonModule],
    templateUrl: './qcm.component.html',
    styleUrls: ['./qcm.component.scss']
})
export class QCMComponent implements OnInit, OnDestroy {
    private _currentUser: Subscription = new Subscription();
    private _data: Subscription = new Subscription();
    public qcm: QCM = {} as QCM;
    public currentUser: User = {} as User;
    public canModify = false;
    public title = 'QCM Brevets';

    constructor(
        private route: ActivatedRoute,
        private _qcmService: QCMService,
        private _userService: UserService
    ) { }

    ngOnInit() {
        // Retreive the prefetched jump
        const data$: Observable<any> = this.route.data;
        this._data = data$.subscribe((data: { qcm: QCM }) => {
            this.qcm = data.qcm;
            if (this.qcm.name == 'bpa') {
                this.title = 'QCM du BPA';
            } else {
                this.title = `QCM Brevets ${this.qcm.name.toUpperCase()}`;
            }
        });
        // Load the current user's data
        const currentUser$: Observable<User> = this._userService.currentUser;
        this._currentUser = currentUser$.subscribe((userData: User) => {
            this.currentUser = userData;
            this.canModify = userData.role === 'Admin';
        });
    }

    ngOnDestroy() {
        this._data.unsubscribe();
        this._currentUser.unsubscribe();
    }
}
