/**
 * This file is part of Anis Client.
 *
 * @copyright Laboratoire d'Astrophysique de Marseille / CNRS
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

import { Component } from '@angular/core';

import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

import * as fromAuth from '../../auth/auth.reducer';
import * as authActions from '../../auth/auth.actions';
import * as authSelector from '../../auth/auth.selector';
import { UserProfile } from '../../auth/user-profile.model';
import { AppConfigService } from '../../app-config.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
    public anisClientVersion: string = '3.6.0';
    public year = (new Date()).getFullYear();
    public isAuthenticated: Observable<boolean>;
    public userProfile: Observable<UserProfile>;
    public userRoles: Observable<string[]>;

    constructor(private store: Store<{ auth: fromAuth.State }>, private config: AppConfigService) {
        this.isAuthenticated = store.select(authSelector.selectIsAuthenticated);
        this.userProfile = store.select(authSelector.selectUserProfile);
        this.userRoles = store.select(authSelector.selectUserRoles);
    }

    authenticationEnabled(): boolean {
        return this.config.authenticationEnabled;
    }

    login(): void {
        this.store.dispatch(authActions.login());
    }

    logout(): void {
        this.store.dispatch(authActions.logout());
    }

    openEditProfile(): void {
        this.store.dispatch(authActions.openEditProfile());
    }

    isAnisAdmin() {
        return this.userRoles.pipe(
            map(roles => roles.includes('anis_admin'))
        );
    }
}