import Account from "./Account";
import Token from "./Token";
import jsonwebtoken from "jsonwebtoken";
import Authorization from "./Authorization";
import { Kind } from "./Kind";


const SECRET = "not really secret";
const DURATION = '4h';
//const DURATION = '10000';

export function token2AuthorizationSet(token : Token) : Array<Authorization>{
    if (token === null && token === undefined)  {
        throw new Error("cannot create token with null or undefined token");
    }
    let payload : {username: string, authorizationSet: Array<Object>} = <{username: string, authorizationSet: Array<Object>}> jsonwebtoken.verify(token.token, SECRET);
    return payload.authorizationSet.map( authorizationObject => {
        const  authorization : {_kind: Kind, _key:string} = <{_kind: Kind, _key:string}> authorizationObject;
        return new Authorization(authorization._kind, authorization._key);
    });
}

export function token2Username(token : Token) : string{
    if (token === null && token === undefined)  {
        throw new Error("cannot create token with null or undefined token");
    }
    let payload : {username: string, authorizationSet: Array<Object>} = <{username: string, authorizationSet: Array<Object>}> jsonwebtoken.verify(token.token, SECRET);
    return payload.username;
}

export function account2Token(account : Account): Token {
    if (account === null && account === undefined)  {
        throw new Error("cannot create token with null or undefined account");
    }
    return new Token(jsonwebtoken.sign({username:account.username, authorizationSet: account.authorizationSet}, SECRET, {expiresIn:DURATION}));
}