-module(ts_timeline).
-export([create_table/1, new/1, new/2, update/1, update/2, write/1, write/2,
         lookup/2, list/3]).

-include("ts_db_records.hrl").
-include_lib("stdlib/include/qlc.hrl").

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

new(TR = #ts_timeline{}) -> ts_common:new(TR).

new(TR = #ts_timeline{}, ExtData) when is_list(ExtData) ->
    ts_common:new(TR, ExtData).

update(TR = #ts_timeline{}) -> ts_common:update(TR).

update(TR = #ts_timeline{}, ExtData) when is_list(ExtData) ->
    ts_common:update(TR, ExtData).

write(TR = #ts_timeline{}) -> mnesia:dirty_write(TR).

write(TR = #ts_timeline{}, ExtData) ->
    {atomic, Result} = mnesia:transaction(fun() ->
        ok = mnesia:write(TR),
        ok = ts_common:do_set_ext_data(TR, ExtData)
    end),
    Result.
    
lookup(Username, TimelineId) ->
    case mnesia:dirty_read(ts_timeline, {Username, TimelineId}) of
        [] -> no_record;
        [Timeline] -> Timeline
    end.

list(Username, Start, Length) -> 
    MatchHead = #ts_timeline{ref = {Username, '_'}, _='_'},
    Timelines = mnesia:dirty_select(ts_timeline, [{MatchHead, [], ['$_']}]),
    lists:sublist(Timelines, Start + 1, Length).
