-module(ts_ext_data).
-export([create_table/1, set_property/3, get_property/2, get_properties/1]).

-include("ts_db_records.hrl").

create_table(TableOpts) ->
    mnesia:create_table(ts_ext_data,
        TableOpts ++ [{attributes, record_info(fields, ts_ext_data)},
                      {type, ordered_set}]).

% set last timeline
set_property(Rec=#ts_user{}, last_timeline, LastTimelineId) ->
    do_set_property(Rec#ts_user.username, last_timeline, LastTimelineId);

% Set exclusion_list for a User account
set_property(Rec=#ts_user{}, entry_exclusions, ExclusionList) ->
    do_set_property(Rec#ts_user.username, entry_exclusions, ExclusionList);

% Set exclusion_list for a Timeline entry
set_property(Rec=#ts_timeline{}, entry_exclusions, ExclusionList) ->
    do_set_property(Rec#ts_timeline.ref, entry_exclusions, ExclusionList);

set_property(Rec, Key, _Value) ->
    throw(lists:flatten(io_lib:format("Property '~s' not available for a ~s record.",
        [Key, element(1, Rec)]))).

get_property(Ref, PropKey) ->
    {atomic, Result} = mnesia:transaction(fun() ->
        case mnesia:read(ts_ext_data, {Ref, PropKey}) of
            [] -> not_set;
            [Property] -> Property#ts_ext_data.value
        end
    end),
    Result.

get_properties(Rec) ->
    Ref = element(2, Rec),
    {atomic, Result} = mnesia:transaction(fun() ->
        MatchHead = #ts_ext_data{ref = {Ref, '_'}, _='_'},
        mnesia:select(ts_ext_data, [{MatchHead, [], ['$_']}])
    end),
    lists:map(fun(ExtData = #ts_ext_data{}) ->
        {Ref, Key} = ExtData#ts_ext_data.ref,
        {Key, ExtData#ts_ext_data.value} end, Result).

do_set_property(Ref, PropKey, Val) ->
    {atomic, _Result} = mnesia:transaction(fun() ->
        mnesia:write(#ts_ext_data{ref = {Ref, PropKey}, value = Val})
    end),
    ok.
