unit backgroundplay;

interface
uses classes;


const MAXRETRIES = 250;
const BGFILE = 'background.list';

type tdonelist = record
album : integer;
track : integer;
end;

type tautoplay = record
  timeout : integer;
end;

var
autoplaymode : boolean;
autoplaying : boolean = false;

procedure initautoplay;
procedure  startautoplay;
procedure stopautoplay;


implementation
uses main,cover,global,sysutils,jukeboxform;

var
donelist : array of tdonelist;
donelistcount : integer = 0;


backgroundlist : array of integer;

procedure initautoplay;
var
bg : tstringlist;
x,y : integer;
t : string;
pth : string;
begin
setlength(backgroundlist,0);
setlength(donelist,0);
donelistcount:=0;
autoplaymode:=true;
randomize;
pth:=paramstr(0);
pth:=ExtractFileDir(pth);

if fileexists(pth+'\'+BGFILE) then begin
 bg:=tstringlist.create;
 try
 bg.LoadFromFile(pth+'\'+BGFILE);
 except;
 exit;
 end;
 for x := 0 to bg.Count-1 do begin
    t:=stringreplace(bg.Strings[x],'__',' - ',[]);
    for y := 0 to mainform.albumlist.Items.Count-1 do begin
      if uppercase(mainform.albumlist.items[y])=uppercase(t) then begin
        setlength(backgroundlist,length(backgroundlist)+1);
        backgroundlist[length(backgroundlist)-1]:=y;
        break;
      end;
    end;

 end;


end;



end;

procedure startautoplay;
var
oktoplay : boolean;
a,t,n : integer;
retrycount : integer;
begin
if jukebox.BackGroundCanAutoPlay=false then exit;

a:=0;
oktoplay:=false;
autoplaying:=true;
t:=0;
retrycount:=0;
mainform.vol.Position:=config.bgvolume;
while oktoplay=false do begin
if length(backgroundlist)=0 then begin
  a:=random(albumcount);
  mainform.albumlist.ItemIndex:=a;
end else begin
  a:=random(length(backgroundlist));
  mainform.albumlist.ItemIndex:=backgroundlist[a];
end;

mainform.albumlistchange(nil);
inc(retrycount);
if (mainform.tracklist.items.count=0) and (retrycount<MAXRETRIES) then begin
   continue;
  end;
oktoplay:=true;

t:=random(mainform.tracklist.items.count-1);
for n:=0 to donelistcount-1 do begin
    if (t=donelist[n].track) and (a=donelist[n].album) then begin
    oktoplay:=false;
    break;
    end;
end;

if retrycount=MAXRETRIES then begin
  setlength(donelist,0);
  donelistcount:=0;
  oktoplay:=true;
end;


end;



setlength(donelist,donelistcount+1);
donelist[donelistcount].album:=a;
donelist[donelistcount].track:=t;
inc(donelistcount);

mainform.cdplayerbutclick(nil);
mainform.cdplayerbut.checked:=true;
mainform.tracklist.itemindex:=t;
mainform.tracklistclick(nil);
mainform.playclick(nil);
//mainform.playlistbutClick(nil);
mainform.playlistbut.checked:=true;
if coverform<>nil then begin
 if coverform.visible=true then begin
 covershow(currentalbumpath,true);
 end;
end;

jukebox.BackgroundTimer.Tag:=0;
jukebox.BackGroundTimerCount:=0;
jukebox.BackgroundTimer.enabled:=true;

end;


procedure stopautoplay;
begin
mainform.vol.Position:=config.volume;
autoplaymode:=false;
autoplaying:=false;
mainform.stopclick(nil);
end;


end.