local createVersion = require('/apis/libversion');

local command = ...;

local function printUsage()
  print('music usage:');
  print();
  print('\t\t\tmusic');
  print('\t\t\tmusic version');
  print('\t\t\tmusic help');
end

if command == 'version' or command == '-version' or command == '--version' then
  print('v' .. createVersion().forSelf());
  return;
end

if command == 'help' or command == '-help' or command == '--help' then
  printUsage();
  return;
end

if command ~= nil and command ~= '' then
  printUsage();
  return;
end

local createMusic = require('/apis/libmusic');
local music = createMusic();

local tracks = music.listTracks();
if #tracks == 0 then
  print('No music found in /data/musics');
  return;
end

if not peripheral.find('speaker') then
  print('No speaker attached');
  return;
end

local createEventLoop = require('/apis/eventloop');
local createTui = require('/apis/libtui');

local eventloop = createEventLoop();
local ui = createTui(eventloop);

local Text = ui.Text;
local Button = ui.Button;
local Box = ui.Box;
local List = ui.List;

local selected = nil;

local function Header()
  return Box({
    direction = 'row',
    bgColor = colors.gray,
    children = {
      Text('Music', {
        flex = 1,
        color = colors.white,
        bgColor = colors.gray,
      }),
      Button('X', {
        color = colors.white,
        bgColor = colors.red,
        onClick = function(tui)
          tui.exitUI('cancel');
        end,
      }),
    },
  });
end

local function TrackList()
  local items = {};
  for _, track in ipairs(tracks) do
    items[#items + 1] = Button(track.name, {
      onClick = function(tui)
        selected = track;
        tui.exitUI('play');
      end,
    });
  end
  return List({
    gap = 1,
    padding = 1,
    children = items,
  });
end

local function App()
  return Box({
    direction = 'column',
    children = {
      Header(),
      Box({
        flex = 1,
        border = true,
        title = 'Choose a track',
        children = {
          TrackList(),
        },
      }),
    },
  });
end

ui.render(App);

if selected then
  print('Playing ' .. selected.name .. '...');
  music.play(selected.path);
  print('Done.');
end
