require "snd"

music_player = obj {
  nam = '@music_player';
  current_music = false;
  current_index = 1;
  music_queue = {};
  loop = false;
  play_now = function(s, m)
    s.music_queue = {}
    s.current_music = m;
    snd.music(m, 1);
  end;
  reset = function(s)
    s.music_queue = {};
    s.current_index = 1;
    snd.stop_music();
  end;
  play_next = function(s, m, c)
    s.music_queue[#s.music_queue + 1] = m;
    if c then
      s.music_queue[#s.music_queue + 1] = c;
    else
      s.music_queue[#s.music_queue + 1] = 1;
    end;
  end;
  tick = function(s)
    if not snd.music_playing() then
      local idx = s.current_index;
      if s.music_queue[idx] then
        s.current_music = s.music_queue[idx];
        snd.music(s.current_music, s.music_queue[idx + 1]);
        local ql = #s.music_queue;
        idx = idx + 2;
        if s.loop and not s.music_queue[idx] then
          if s.loop ~= true then
            s.loop = s.loop - 1;
          end;
          idx = 1;
        end;
        s.current_index = idx;
      elseif s.current_music then
        snd.music(s.current_music, 1);
      end;
    end;
  end;
}