import {Injectable} from '@angular/core';
import { Plugins } from '@capacitor/core';
import {JwtHelperService} from '@auth0/angular-jwt';
import {Observable} from 'rxjs';

const { Storage } = Plugins;

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

    constructor(private jwtHelper: JwtHelperService) {
    }

    public getToken(): Observable<string> {
        return new Observable<string>(observer => {
            Storage.get({key: 'token'}).then(val => {
               observer.next(val.value);
               observer.complete();
            });
        });
    }

    public setToken(token: string): void {
        Storage.set({key: 'token', value: token});
    }

    public removeToken(): void {
        Storage.remove({key: 'token'});
    }

    public authenticated(): Observable<boolean> {
        return new Observable<boolean>(observer => {
          this.getToken().subscribe(token => {
            if (token === null) {
                observer.next(false);
            } else {
                observer.next(!this.jwtHelper.isTokenExpired(token));
            }
            observer.complete();
          });
        });
    }

}
