commit 6e81da4c9cc68a4b3fe7e20b4747237f61a5128c Author: Noah Metz Date: Thu Jan 25 22:41:16 2024 -0700 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..df53f7d --- /dev/null +++ b/.gitignore @@ -0,0 +1,20 @@ +.rebar3 +_build +_checkouts +_vendor +.eunit +*.o +*.beam +*.plt +*.swp +*.swo +.erlang.cookie +ebin +log +erl_crash.dump +.rebar +logs +.idea +*.iml +rebar3.crashdump +*~ diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..d6bff50 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,186 @@ +# Apache License +Version 2.0, January 2004 + +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +## 1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and +distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright +owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities +that control, are controlled by, or are under common control with that entity. +For the purposes of this definition, "control" means (i) the power, direct or +indirect, to cause the direction or management of such entity, whether by +contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the +outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising +permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including +but not limited to software source code, documentation source, and configuration +files. + +"Object" form shall mean any form resulting from mechanical transformation or +translation of a Source form, including but not limited to compiled object code, +generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made +available under the License, as indicated by a copyright notice that is included +in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that +is based on (or derived from) the Work and for which the editorial revisions, +annotations, elaborations, or other modifications represent, as a whole, an +original work of authorship. For the purposes of this License, Derivative Works +shall not include works that remain separable from, or merely link (or bind by +name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version +of the Work and any modifications or additions to that Work or Derivative Works +thereof, that is intentionally submitted to Licensor for inclusion in the Work +by the copyright owner or by an individual or Legal Entity authorized to submit +on behalf of the copyright owner. For the purposes of this definition, +"submitted" means any form of electronic, verbal, or written communication sent +to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, and +issue tracking systems that are managed by, or on behalf of, the Licensor for +the purpose of discussing and improving the Work, but excluding communication +that is conspicuously marked or otherwise designated in writing by the copyright +owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf +of whom a Contribution has been received by Licensor and subsequently +incorporated within the Work. + +## 2. Grant of Copyright License. + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable copyright license to reproduce, prepare Derivative Works of, +publicly display, publicly perform, sublicense, and distribute the Work and such +Derivative Works in Source or Object form. + +## 3. Grant of Patent License. + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable (except as stated in this section) patent license to make, have +made, use, offer to sell, sell, import, and otherwise transfer the Work, where +such license applies only to those patent claims licensable by such Contributor +that are necessarily infringed by their Contribution(s) alone or by combination +of their Contribution(s) with the Work to which such Contribution(s) was +submitted. If You institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Work or a +Contribution incorporated within the Work constitutes direct or contributory +patent infringement, then any patent licenses granted to You under this License +for that Work shall terminate as of the date such litigation is filed. + +## 4. Redistribution. + +You may reproduce and distribute copies of the Work or Derivative Works thereof +in any medium, with or without modifications, and in Source or Object form, +provided that You meet the following conditions: + +1. You must give any other recipients of the Work or Derivative Works a copy of + this License; and + +2. You must cause any modified files to carry prominent notices stating that + You changed the files; and + +3. You must retain, in the Source form of any Derivative Works that You + distribute, all copyright, patent, trademark, and attribution notices from + the Source form of the Work, excluding those notices that do not pertain to + any part of the Derivative Works; and + +4. If the Work includes a "NOTICE" text file as part of its distribution, then + any Derivative Works that You distribute must include a readable copy of the + attribution notices contained within such NOTICE file, excluding those + notices that do not pertain to any part of the Derivative Works, in at least + one of the following places: within a NOTICE text file distributed as part + of the Derivative Works; within the Source form or documentation, if + provided along with the Derivative Works; or, within a display generated by + the Derivative Works, if and wherever such third-party notices normally + appear. The contents of the NOTICE file are for informational purposes only + and do not modify the License. You may add Your own attribution notices + within Derivative Works that You distribute, alongside or as an addendum to + the NOTICE text from the Work, provided that such additional attribution + notices cannot be construed as modifying the License. + +You may add Your own copyright statement to Your modifications and may provide +additional or different license terms and conditions for use, reproduction, or +distribution of Your modifications, or for any such Derivative Works as a whole, +provided Your use, reproduction, and distribution of the Work otherwise complies +with the conditions stated in this License. + +## 5. Submission of Contributions. + +Unless You explicitly state otherwise, any Contribution intentionally submitted +for inclusion in the Work by You to the Licensor shall be under the terms and +conditions of this License, without any additional terms or conditions. +Notwithstanding the above, nothing herein shall supersede or modify the terms of +any separate license agreement you may have executed with Licensor regarding +such Contributions. + +## 6. Trademarks. + +This License does not grant permission to use the trade names, trademarks, +service marks, or product names of the Licensor, except as required for +reasonable and customary use in describing the origin of the Work and +reproducing the content of the NOTICE file. + +## 7. Disclaimer of Warranty. + +Unless required by applicable law or agreed to in writing, Licensor provides the +Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, +including, without limitation, any warranties or conditions of TITLE, NON- +INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are +solely responsible for determining the appropriateness of using or +redistributing the Work and assume any risks associated with Your exercise of +permissions under this License. + +## 8. Limitation of Liability. + +In no event and under no legal theory, whether in tort (including negligence), +contract, or otherwise, unless required by applicable law (such as deliberate +and grossly negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, incidental, +or consequential damages of any character arising as a result of this License or +out of the use or inability to use the Work (including but not limited to +damages for loss of goodwill, work stoppage, computer failure or malfunction, or +any and all other commercial damages or losses), even if such Contributor has +been advised of the possibility of such damages. + +## 9. Accepting Warranty or Additional Liability. + +While redistributing the Work or Derivative Works thereof, You may choose to +offer, and charge a fee for, acceptance of support, warranty, indemnity, or +other liability obligations and/or rights consistent with this License. However, +in accepting such obligations, You may act only on Your own behalf and on Your +sole responsibility, not on behalf of any other Contributor, and only if You +agree to indemnify, defend, and hold each Contributor harmless for any liability +incurred by, or claims asserted against, such Contributor by reason of your +accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +Copyright 2024, Noah Metz . + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..bf658a8 --- /dev/null +++ b/README.md @@ -0,0 +1,9 @@ +erlk +===== + +An OTP application + +Build +----- + + $ rebar3 compile diff --git a/rebar.config b/rebar.config new file mode 100644 index 0000000..4dcc2a7 --- /dev/null +++ b/rebar.config @@ -0,0 +1,12 @@ +{erl_opts, [debug_info]}. + +{deps, [ + {emqtt, {git, "https://github.com/emqx/emqtt", {tag, "1.10.0"}}}, + {jsone, {git, "https://github.com/sile/jsone"}}, + {sqlite3, {git, "https://github.com/Xelynega/erlang-sqlite3"}} +]}. + +{shell, [ + % {config, "config/sys.config"}, + {apps, [erlk]} +]}. diff --git a/rebar.lock b/rebar.lock new file mode 100644 index 0000000..3338be3 --- /dev/null +++ b/rebar.lock @@ -0,0 +1,35 @@ +{"1.2.0", +[{<<"cowlib">>,{pkg,<<"cowlib">>,<<"2.12.1">>},1}, + {<<"emqtt">>, + {git,"https://github.com/emqx/emqtt", + {ref,"71000c5276690db06c0cc290b3fcb78635a0b92e"}}, + 0}, + {<<"getopt">>,{pkg,<<"getopt">>,<<"1.0.2">>},1}, + {<<"gun">>, + {git,"https://github.com/emqx/gun", + {ref,"4faea40b9a8ca1eac5288355f8202e0cea379d50"}}, + 1}, + {<<"jsone">>, + {git,"https://github.com/sile/jsone", + {ref,"fd911a20ae0bd7454962733668812ebee2379abe"}}, + 0}, + {<<"quicer">>, + {git,"https://github.com/emqx/quic.git", + {ref,"7fe30c762498139350990f848640fea5d59667b3"}}, + 1}, + {<<"snabbkaffe">>, + {git,"https://github.com/kafka4beam/snabbkaffe.git", + {ref,"69058948359a3cffba1d5fe4575d136e3fbb3b11"}}, + 2}, + {<<"sqlite3">>, + {git,"https://github.com/Xelynega/erlang-sqlite3", + {ref,"5703b047a8ff66450a4de13af37cee10dfe656d5"}}, + 0}]}. +[ +{pkg_hash,[ + {<<"cowlib">>, <<"A9FA9A625F1D2025FE6B462CB865881329B5CAFF8F1854D1CBC9F9533F00E1E1">>}, + {<<"getopt">>, <<"33D9B44289FE7AD08627DDFE1D798E30B2DA0033B51DA1B3A2D64E72CD581D02">>}]}, +{pkg_hash_ext,[ + {<<"cowlib">>, <<"163B73F6367A7341B33C794C4E88E7DBFE6498AC42DCD69EF44C5BC5507C8DB0">>}, + {<<"getopt">>, <<"A0029AEA4322FB82A61F6876A6D9C66DC9878B6CB61FAA13DF3187384FD4EA26">>}]} +]. diff --git a/src/erlk.app.src b/src/erlk.app.src new file mode 100644 index 0000000..2ad6d04 --- /dev/null +++ b/src/erlk.app.src @@ -0,0 +1,18 @@ +{application, erlk, + [{description, "erlang Event Kontrol"}, + {vsn, "0.1.0"}, + {registered, []}, + {mod, {erlk_app, []}}, + {applications, + [kernel, + stdlib, + jsone, + emqtt, + sqlite3 + ]}, + {env,[]}, + {modules, []}, + + {licenses, ["Apache-2.0"]}, + {links, []} + ]}. diff --git a/src/erlk_app.erl b/src/erlk_app.erl new file mode 100644 index 0000000..290e7b7 --- /dev/null +++ b/src/erlk_app.erl @@ -0,0 +1,18 @@ +%%%------------------------------------------------------------------- +%% @doc erlk public API +%% @end +%%%------------------------------------------------------------------- + +-module(erlk_app). + +-behaviour(application). + +-export([start/2, stop/1]). + +start(_StartType, _StartArgs) -> + erlk_sup:start_link(). + +stop(_State) -> + ok. + +%% internal functions diff --git a/src/erlk_sup.erl b/src/erlk_sup.erl new file mode 100644 index 0000000..4bbf005 --- /dev/null +++ b/src/erlk_sup.erl @@ -0,0 +1,41 @@ +%%%------------------------------------------------------------------- +%% @doc erlk top level supervisor. +%% @end +%%%------------------------------------------------------------------- + +-module(erlk_sup). + +-behaviour(supervisor). + +-export([start_link/0]). + +-export([init/1]). + +-define(SERVER, ?MODULE). + +start_link() -> + supervisor:start_link(?MODULE, []). + +%% sup_flags() = #{strategy => strategy(), % optional +%% intensity => non_neg_integer(), % optional +%% period => pos_integer()} % optional +%% child_spec() = #{id => child_id(), % mandatory +%% start => mfargs(), % mandatory +%% restart => restart(), % optional +%% shutdown => shutdown(), % optional +%% type => worker(), % optional +%% modules => modules()} % optional + +init(_) -> + SupFlags = #{strategy => rest_for_one}, + ChildSpecs = [ + #{id => mqtt, + start => {mqtt, start_link, []} + }, + #{id => event_mgr, + start => {event_mgr, start_link, [[mqtt, none]]} + } + ], + {ok, {SupFlags, ChildSpecs}}. + +%% internal functions diff --git a/src/event_mgr.erl b/src/event_mgr.erl new file mode 100644 index 0000000..df0e331 --- /dev/null +++ b/src/event_mgr.erl @@ -0,0 +1,113 @@ +-module(event_mgr). + +-behaviour(gen_server). + +-export([start_link/1, init/1, handle_cast/2, update_config/2, handle_call/3]). + +-record(event_config, {database_file = none, skills_fields = [], practice_fields = [], divisions = []}). + +-record(division_config, {fields = [], teams = [], teams_hash = "", practice_matches = [], practice_rounds = 0, practice_seed = 0, qualification_matches = [], qualification_rounds = [], qualification_seed = 0, elimination_alliances = 0}). + +-record(event_state, {owner, config = #event_config{}, fields = [], database = none, supervisor}). + +start_link(Args) -> + gen_server:start_link({local, ?MODULE}, ?MODULE, Args, []). + +init([Owner, none]) -> + {ok, Supervisor} = event_sup:start_link(), + {ok, #event_state{owner = Owner, supervisor = Supervisor}}; +init([Owner, ConfigJSON]) -> + {ok, Supervisor} = event_sup:start_link(), + {ok, parse_event_config(ConfigJSON, #event_state{owner = Owner, supervisor = Supervisor})}. + +get_matches_from_db(Database, Division, Round, Seed, Size, TeamsHash) -> + if Size == 0 -> []; + Size > 0 -> SQL = io_lib:format("SELECT number, blue_1, blue_2, red_1, red_2 FROM matches WHERE division = '~p' AND round = '~p' AND size = '~p' AND seed = '~p' AND teams = '~s';", [Division, Round, Size, Seed, TeamsHash]), + [{columns, Columns}, {rows, Rows}] = sqlite3:sql_exec(Database, SQL), + [] + end. + +parse_division([], _, Parsed, Fields, _) -> {Parsed, Fields}; +parse_division([Division | Divisions], Database, Parsed, Fields, N) -> + TeamsBinary = maps:get(<<"teams">>, Division), + TeamsList = [binary_to_list(X) || X <- TeamsBinary], + TeamsHash = schedule:hash_teams_list(TeamsList), + + PracticeRounds = maps:get(<<"practice_rounds">>, Division), + PracticeSeed = maps:get(<<"practice_seed">>, Division), + PracticeMatches = get_matches_from_db(Database, N, practice, PracticeSeed, PracticeRounds, TeamsHash), + + QualificationRounds = maps:get(<<"qualification_rounds">>, Division), + QualificationSeed = maps:get(<<"qualification_seed">>, Division), + QualificationMatches = get_matches_from_db(Database, N, qualification, QualificationSeed, PracticeRounds, TeamsHash), + + DivConfig = #division_config{ + fields = [binary_to_list(X) || X <- maps:get(<<"fields">>, Division)], + elimination_alliances = maps:get(<<"elimination_alliances">>, Division), + practice_rounds = PracticeRounds, + practice_matches = PracticeMatches, + practice_seed = PracticeSeed, + qualification_rounds = QualificationRounds, + qualification_matches = QualificationMatches, + qualification_seed = QualificationSeed, + teams = TeamsList, + teams_hash = TeamsHash + }, + parse_division(Divisions, Database, [DivConfig | Parsed], lists:append([DivConfig#division_config.fields, Fields]), N+1). + +parse_divisions(Divisions, Database) -> + parse_division(Divisions, Database, [], [], 0). + + +parse_event_config(ConfigJSON, State) -> + Config = jsone:decode(list_to_binary(ConfigJSON)), + CurrentFile = State#event_state.config#event_config.database_file, + NewFile = binary_to_list(maps:get(<<"database">>, Config)), + {ok, Database} = if CurrentFile == NewFile -> {ok, State#event_state.database}; + CurrentFile == none -> sqlite3:open(anonymous, [{file, NewFile}]); + true -> sqlite3:close(State#event_state.database), sqlite3:open(anonymous, [{file, NewFile}]) + end, + {Divisions, DivisionFields} = parse_divisions(maps:get(<<"divisions">>, Config), Database), + PracticeFields = [binary_to_list(X) || X <- maps:get(<<"testing_fields">>, Config)], + SkillsFields = [binary_to_list(X) || X <- maps:get(<<"skills_fields">>, Config)], + EliminationFields = [binary_to_list(X) || X <- maps:get(<<"elimination_fields">>, Config)], + Fields = sets:to_list(sets:from_list(lists:append([DivisionFields, SkillsFields, PracticeFields, EliminationFields]))), + + FieldStates = update_fields(Fields, State#event_state.fields), + State#event_state{config = #event_config{ + database_file = binary_to_list(maps:get(<<"database">>, Config)), + skills_fields = SkillsFields, + practice_fields = PracticeFields, + divisions = Divisions + }, fields = FieldStates, database = Database}. + +update_config(Server, ConfigJSON) -> + gen_server:call(Server, {event_config, ConfigJSON}). + +get_field_state(_, []) -> free; +get_field_state(Name, [{FieldName, FieldState} | FieldStates]) -> + if Name == FieldName -> FieldState; + true -> get_field_state(Name, FieldStates) + end. + +start_next_event(State) -> + State. + +update_fields(Fields, FieldStates) -> + GetState = fun(Name) -> get_field_state(Name, FieldStates) end, + lists:zip(Fields, lists:map(GetState, Fields)). + +handle_call({event_config, ConfigJSON}, _, State) -> + NewState = parse_event_config(ConfigJSON, State), + % TODO: calculate which events should be running + % TODO: stop events on fields that no longer exist + % TODO: stop events on fields that are running the wrong event + % TODO: start every event that should be running given the config + State#event_state.owner ! {new_event_config, NewState#event_state.config}, + {reply, ok, NewState}; + +handle_call(event_done, _From, State) -> + {noreply, start_next_event(State)}. + +handle_cast(_, State) -> + {noreply, State}. diff --git a/src/event_sup.erl b/src/event_sup.erl new file mode 100644 index 0000000..fc0189a --- /dev/null +++ b/src/event_sup.erl @@ -0,0 +1,15 @@ +-module(event_sup). + +-behaviour(supervisor). + +-export([start_link/0, init/1]). + +start_link() -> + supervisor:start_link(?MODULE, []). + +init([]) -> + io:fwrite("SUP_INIT~n"), + SupFlags = #{strategy => one_for_one, + intensity => 0, + period => 1}, + {ok, {SupFlags, []}}. diff --git a/src/mqtt.erl b/src/mqtt.erl new file mode 100644 index 0000000..e74440f --- /dev/null +++ b/src/mqtt.erl @@ -0,0 +1,23 @@ +-module(mqtt). + +-behaviour(gen_server). + +-export([start_link/0, init/1, handle_cast/2, handle_info/2, handle_call/3]). + +start_link() -> + gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). + +init(_) -> + {ok, PID} = emqtt:start_link(), + {ok, Props} = emqtt:connect(PID), + {ok, {PID, Props}}. + +handle_info(Request, State) -> + io:fwrite("~p~n", [Request]), + {noreply, State}. + +handle_cast(_, State) -> + {noreply, State}. + +handle_call(_, _, State) -> + {noreply, State}. diff --git a/src/schedule.erl b/src/schedule.erl new file mode 100644 index 0000000..ffba69b --- /dev/null +++ b/src/schedule.erl @@ -0,0 +1,127 @@ +-module(schedule). + +-behaviour(gen_server). + +-export([start_link/0, init/1, handle_cast/2, handle_call/3]). + +-export([remove/2, generate/3, write/6, pick_teams/2, pick_matches/1, hash_teams_list/1, init_db/1]). + +start_link() -> + gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). + +init([]) -> + rand:seed(default), + {ok, []}. + +handle_cast(_, State) -> + {noreply, State}. + +remove(List, Index) -> + [X || {I, X} <- lists:enumerate(0, List), I /= Index]. + +duplicate(1, Original, Constructed) -> lists:append(Original, Constructed); +duplicate(N, Original, Constructed) -> duplicate(N-1, Original, lists:append(Original, Constructed)). + +duplicate(List, N) -> duplicate(List, N, []). + +padding(Size) when Size >= 4 -> (4 - (Size rem 4)) rem 4. + +fill_padding_match([], Teams, Filled) -> {Filled, Teams}; +fill_padding_match([padding | Left], [Picked | Teams], Filled) -> + Duplicate = lists:member(Picked, Left) or lists:member(Picked, Filled), + if Duplicate -> fill_padding_match([padding | Left], lists:append(Teams, [Picked]), Filled); + true -> fill_padding_match(Left, Teams, [Picked | Filled]) + end; +fill_padding_match([Team | Left], Teams, Filled) -> + fill_padding_match(Left, Teams, [Team | Filled]). + +fill_padding_match(Match, Teams) -> + fill_padding_match(Match, Teams, []). + +fill_padding_schedule(Matches, Teams) -> + TeamsRandom = [X || {_, X} <- lists:sort([{rand:uniform(), N} || N <- Teams])], + {Schedule, _} = lists:mapfoldl(fun fill_padding_match/2, TeamsRandom, Matches), + Schedule. + +hash_teams_list(Teams) -> + [ Y || <> <= crypto:hash(sha, Teams), Y <- integer_to_list(X,16)]. + +init_db(File) -> + IsFile = filelib:is_regular(File), + if IsFile -> file:delete(File) end, + {ok, Database} = sqlite3:open(anonymous, [{file, File}]), + ok = sqlite3:create_table(Database, matches, [{division, integer, [not_null]}, + {round, text, [not_null]}, + {size, integer, [not_null]}, + {teams, text, [not_null]}, + {number, integer, [not_null]}, + {seed, integer, [not_null]}, + {red_1, text, [not_null]}, + {red_2, text, [not_null]}, + {blue_1, text, [not_null]}, + {blue_2, text, [not_null]}], + [{primary_key, [division, round, size, teams, number, seed]}]), + ok = sqlite3:create_table(Database, match_scores, [{division, integer, [not_null]}, + {round, text, [not_null]}, + {size, integer, [not_null]}, + {teams, text, [not_null]}, + {number, integer, [not_null]}, + {seed, integer, [not_null]}, + {instance, integer, [not_null]}, + {score, blob, [not_null]}], + [{primary_key, [division, round, size, teams, number, seed, instance]}, + {foreign_key, {[division, round, size, teams, number, seed], matches, [division, round, size, teams, number, seed], "ON DELETE CASCADE"}}]), + ok = sqlite3:create_table(Database, match_states, [{division, integer, [not_null]}, + {round, text, [not_null]}, + {size, integer, [not_null]}, + {teams, text, [not_null]}, + {number, integer, [not_null]}, + {seed, integer, [not_null]}, + {time, integer, [not_null]}, + {state, blob, [not_null]}], + [{primary_key, [division, round, size, teams, number, seed, time]}, + {foreign_key, {[division, round, size, teams, number, seed], matches, [division, round, size, teams, number, seed], "ON DELETE CASCADE"}}]), + sqlite3:close(Database). + +write(DatabaseFile, Division, Round, Seed, Matches, Teams) -> + MatchList = generate(Seed, Matches, Teams), + Schedule = [[{division, Division}, + {round, atom_to_list(Round)}, + {size, Matches}, + {teams, hash_teams_list(Teams)}, + {number, N}, + {seed, Seed}, + {blue_1, B1}, + {blue_2, B2}, + {red_1, R1}, + {red_2, R2}] || {N, [B1, B2, R1, R2]} <- lists:enumerate(MatchList)], + {ok, Database} = sqlite3:open(anonymous, [{file, DatabaseFile}]), + [ok | _] = sqlite3:write_many(Database, matches, Schedule), + ok = sqlite3:close(Database). + + +generate(Seed, Matches, Teams) -> + TeamsRepeated = duplicate(Matches, Teams), + TeamsPadded = TeamsRepeated ++ lists:duplicate(padding(length(Teams)*Matches), padding), + rand:seed(default, Seed), + TeamsRandom = [X || {_, X} <- lists:sort([{rand:uniform(), N} || N <- TeamsPadded])], + fill_padding_schedule(pick_matches(TeamsRandom), Teams). + +pick_teams(Teams, Picked, 0, Safety) when Safety > 0 -> {Teams, Picked}; +pick_teams([Team | Teams], Picked, N, Safety) when Safety > 0 -> + Duplicate = lists:member(Team, Picked), + if Duplicate, Team =/= padding -> pick_teams(lists:append(Teams, [Team]), Picked, N, Safety - 1); + true -> pick_teams(Teams, [Team | Picked], N-1, Safety) + end. + +pick_teams(Teams, N) -> pick_teams(Teams, [], N, 1000). + +pick_matches([], Matches) -> Matches; +pick_matches(Teams, Matches) -> + {NewTeams, Match} = pick_teams(Teams, 4), + pick_matches(NewTeams, [Match | Matches]). + +pick_matches(Teams) -> pick_matches(Teams, []). + +handle_call(Req, _, State) -> + {reply, Req, State}.