import {HttpClient} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {BehaviorSubject, Subject} from 'rxjs';
import {Authorization} from '../models/Authorization';
import { Layout } from "../widgets/Layout";
import { PageService } from './page.service';
import { TranslateService } from '@ngx-translate/core';
import { Configuration } from '../models/Page';
import { User } from '../models/User';
import { Community } from '../models/Community';

@Injectable({
    providedIn: 'root'
})
export class AppService {

    private authorization?: Authorization;
    private authorizationSubject: BehaviorSubject<any> = new BehaviorSubject<any>(null);
    private pageDetailSubject: Subject<any> = new Subject<any>();
    
    user: User = new User();
    
    community: Community = new Community();

    constructor(private http: HttpClient, private pageService: PageService) {
        const latestAuthorization = sessionStorage.getItem("authorization");
        this.setAuthorization(latestAuthorization ? JSON.parse(latestAuthorization) : null);
    }

    onAuthorizationDone() {
        return this.authorizationSubject;
    }

    setLanguage(translateService: TranslateService, lang: string) {
        sessionStorage.setItem("lang", lang);
        translateService.use(lang);
    }

    getLanguage() {
        return sessionStorage.getItem("lang");
    }

    setAuthorization(authorization: Authorization) {
        this.authorization = authorization;
        sessionStorage.setItem("authorization", JSON.stringify(this.authorization));
        this.authorizationSubject.next(this.authorization);
    }

    removeAuthorization() {
        this.authorization = new Authorization();
        sessionStorage.removeItem("authorization");
        this.authorizationSubject.next(this.authorization);
    }

    isLoggedIn() {
        return this.authorization && this.authorization.authenticated
    }

    getPageConfiguration(slug: string) {
        this.http.get("lecservice/page-configuration/" + slug).subscribe(
            (serviceResponse: any) => {
                if (serviceResponse.success) {
                    // this.pageDetailSubject.next(Configuration.fromJson(serviceResponse.result))
                    this.pageDetailSubject.next(serviceResponse.result);
                } else {
                    this.pageDetailSubject.next(null)
                }
            });
    }
}

