-module(ts_api_session).
-compile(export_all).

-include("ts_db_records.hrl").
-include("yaws_api.hrl").

%  6 hours: sec min hr
-define(TTL, 60*60* 6).

new(Username) -> 
    Session = #ts_api_session{ username = Username },

    CookieVal = yaws_api:new_cookie_session(Session, ?TTL),
    {CookieVal, Session}.

logout(CookieVal) ->
    yaws_api:delete_cookie_session(CookieVal).

get_session(YArg) ->
    % get the cookie header
    Cookie = (YArg#arg.headers)#headers.cookie,

    % look up the cookie in the session server
    case yaws_api:find_cookie_val("ts_api_session", Cookie) of

    % no cookie, not logged in
    [] -> not_logged_in;

    % found the cookie
    CookieVal -> 

        % get the session data
        case yaws_api:cookieval_to_opaque(CookieVal) of
            {error, _Err} -> session_expired;
            {ok, Session} -> Session
        end
    end.
