import { Cookie } from 'ng2-cookies/ng2-cookies';

import { IToken } from '../token';

let LOANREQUESTID_COOKIE_NAME: string = 'loanRequestId';
let LOANREQUESTUID_COOKIE_NAME: string = 'loanRequestUid';
let LEADUID_COOKIE_NAME: string = 'leaduid';
let TOKEN_COOKIE_NAME: string = 'Knk-token';

export class LdiStorage {
    private static cookiesNames = [LOANREQUESTID_COOKIE_NAME, LOANREQUESTUID_COOKIE_NAME, LEADUID_COOKIE_NAME, TOKEN_COOKIE_NAME];
    public static Clear(): void {
        LdiStorage.cookiesNames.forEach(cookie => {
            LdiStorage.DeleteFromCookies(cookie);
        });
    }

    public static SaveToken(token: IToken): void {
        // save expiry /2  from server expiry
        LdiStorage.SaveToCookies(TOKEN_COOKIE_NAME, token, token.expiry / 2 / 60 / 60 / 24);
    }
    public static SaveLoanRequestId(loanRequestId: number): void {
        LdiStorage.SaveToCookies(LOANREQUESTID_COOKIE_NAME, loanRequestId);
    }
    public static SaveLoanRequestUid(loanRequestUid: string): void {
        LdiStorage.SaveToCookies(LOANREQUESTUID_COOKIE_NAME, loanRequestUid);
    }
    public static SaveLeadUid(leadUid: string): void {
        LdiStorage.SaveToCookies(LEADUID_COOKIE_NAME, leadUid);
    }

    public static DeleteToken(): void {
        LdiStorage.DeleteFromCookies(TOKEN_COOKIE_NAME);
    }
    public static DeleteLoanRequestId(): void {
        LdiStorage.DeleteFromCookies(LOANREQUESTID_COOKIE_NAME);
    }
    public static DeleteLoanRequestUid(): void {
        LdiStorage.DeleteFromCookies(LOANREQUESTUID_COOKIE_NAME);
    }
    public static DeleteLeadUid(): void {
        LdiStorage.DeleteFromCookies(LEADUID_COOKIE_NAME);
    }

    public static get Token(): IToken {
        return <IToken>LdiStorage.LoadFromCookies(TOKEN_COOKIE_NAME);
    }

    public static get LoanRequestId(): number {
        return <number>LdiStorage.LoadFromCookies(LOANREQUESTID_COOKIE_NAME);
    }

    public static get LoanRequestUid(): string {
        return <string>LdiStorage.LoadFromCookies(LOANREQUESTUID_COOKIE_NAME);
    }
    public static get LeadUid(): string {
        return <string>LdiStorage.LoadFromCookies(LEADUID_COOKIE_NAME);
    }
    private static SaveToCookies(cookieName: string, value: Object, expires: number = 1, path: string = '/'): void {
        Cookie.set(cookieName, JSON.stringify(value), expires, path);
    }
    private static DeleteFromCookies(cookieName: string, path: string = '/'): void {
        Cookie.delete(cookieName, path);
    }
    private static LoadFromCookies(cookiesName: string): {} {
        const value: string = Cookie.get(cookiesName);
        if (value) {
            return JSON.parse(value);
        }
        return null;
    }
}
