#include "usermaster.h"
#include "entry.h"
#include <vector>
using namespace std;

entry* usermaster::org(entry &bucket, entry* &pool, int &nextfree, const int &POOLSIZE)
{
   int result=finduser(bucket.djname);             //get index of user array to traverse

   entry* seek=userlist[result].head;
   if(seek!=NULL)                            //if there is at least one entry already
   {
      while(seek->nextsong!=NULL)            //traverse down existing list of entries
         seek=seek->nextsong;

      seek->nextsong=newentry(bucket,pool,nextfree,POOLSIZE); //create & instantiate the new entry

      return seek->nextsong;                 //return address to be X-ref'd
   }
                                             //otherwise make new at the head
   userlist[result].head=newentry(bucket,pool,nextfree,POOLSIZE);

   return userlist[result].head;
}

entry* usermaster::newentry(entry &bucket, entry* &pool, int &nextfree, const int &POOLSIZE)
{
   if(nextfree==POOLSIZE)
   {
      cout<<"No space left!";
      abort();
   }
   pool[nextfree]=bucket;                             //copy it on over
   pool[nextfree].nextsong=NULL;
   pool[nextfree].nextuser=NULL;
   nextfree++;
   return pool+nextfree-1;
}

int usermaster::finduser(const apstring &username)
{
   for(int here=0; here<int(userlist.size()); here++)
      if(userlist[here].djname==username)
         return here;                        //return location of instance of user in user array

                                             //username is not found in userlist
   return pushuser(username);                //so push it on to end of list and return that
}

int usermaster::pushuser(const apstring &username)
{
                                             //couldn't this all be done in a constructor?
   userlist.resize(int(userlist.size())+1);     //allocate new element in array
   userlist[int(userlist.size())-1].djname=username;
   userlist[int(userlist.size())-1].head=NULL;

   return int(userlist.size())-1;               //return the index of this new element
}

entry* usermaster::findsong(int &userno,const apstring &songname, const apstring &t_mode)
{
   entry* sentinel=userlist[userno].head;
   while(sentinel!=NULL && (sentinel->title!=songname || sentinel->mode!=t_mode))
      sentinel=sentinel->nextsong;
   if(sentinel!=NULL)
      return sentinel;
   return NULL;
}
