import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';

@Injectable()
export class TokenStorage {
	/**
	 * Get access token
	 * @returns {Observable<string>}
	 */
	public getAccessToken(): string {
		const token: any = localStorage.getItem('accessTokenDrenax');
		try {
			return token;
		} catch (e) {}
	}

	/**
	 * Get refresh token
	 * @returns {Observable<string>}
	 */
	public getRefreshToken(): Observable<string> {
		const token: string = <string>localStorage.getItem('refreshTokenDrenax');
		return of(token);
	}

	/**
	 * Get user roles in JSON string
	 * @returns {Observable<any>}
	 */
	public getUserRoles(): Observable<any> {
		const roles: any = localStorage.getItem('userRolesDrenax');
		try {
			return JSON.parse(roles)
		} catch (e) {}
	}

	/**
	 * Get user in JSON string
	 * @returns {Observable<any>}
	 */
	public getUser(): any {
		const user: any = localStorage.getItem('userDrenax');

		try {
			return JSON.parse(user);
		} catch (e) {}
	}

	/**
	 * Set access token
	 * @returns {TokenStorage}
	 */
	public setAccessToken(token: string): TokenStorage {
		localStorage.setItem('accessTokenDrenax', token);

		return this;
	}

	/**
	 * Set refresh token
	 * @returns {TokenStorage}
	 */
	public setRefreshToken(token: string): TokenStorage {
		localStorage.setItem('refreshTokenDrenax', token);

		return this;
	}

	/**
	 * Set user roles
	 * @param roles
	 * @returns {TokenStorage}
	 */
	public setUserRoles(roles: any): any {
		if (roles != null) {
			localStorage.setItem('userRolesDrenax', JSON.stringify(roles));
		}

		return this;
	}

	/**
	 * Set user
	 * @param user
	 * @returns {TokenStorage}
	 */
	public setUser(user: any): any {
		if (user != null) {
			localStorage.setItem('userDrenax', JSON.stringify(user));
		}

		return this;
	}

	/**
	 * Remove tokens
	 */
	public clear() {
		localStorage.removeItem('accessTokenDrenax');
		localStorage.removeItem('refreshTokenDrenax');
		localStorage.removeItem('userRolesDrenax');
		localStorage.removeItem('userDrenax');
	}
}
