package app.mar.game.scheduler;

import android.util.Log;

import java.io.Serializable;
import java.util.ArrayList;

import app.mar.activities.ChallengeDriver;
import app.mar.game.Event;
import app.mar.game.Game;
import app.mar.game.Resource;
import app.mar.game.challenges.Challenge;


public class Scheduler implements Serializable {

    protected Task mStart;
    protected Task mLastTask;

    public Scheduler() {
    }

    public String toString()
    {
        String out = "[ ";
        Task t = mStart;
        for(t=mStart; t!=null; t=t.next()) {
            if(t!=mStart) out+=", ";
            out+=t.toString();
        }
        return out+" ]";
    }

    private void append(Task t)
    {
        //Log.e("___SCHEDULER_DEBUG___AP", "Ajout de : "+t.toString()+" : "+toString());
        if(mStart==null) mStart=t;
        else mStart.enqueue(t);
        Log.e("___", "ok");
    }

    public void append(Challenge c)
    {
        ArrayList<Event> a = c.getStartEvent();
        ArrayList<Event> b = c.getEndEvent();

        append(a);
        append(new ChallengeTask(c));
        append(b);
    }


    public void append(Resource c){ append(new ResourceTask(c));}
    public void append(Event c){ append(new EventTask(c));}
    public void append(int x){ append(new SpecialTask(x));}


    public void append(ArrayList<?> cc) {
        ArrayList<Object> c = (ArrayList<Object>) cc;
        for(int i=0; i<c.size(); i++)
            if(c.get(i) instanceof Resource)
                append(new ResourceTask((Resource)c.get(i)));
            else if(c.get(i) instanceof Event)
                append(new EventTask((Event)c.get(i)));
    }

    public void prepend(Resource r) { prepend(new ResourceTask(r));}
    public void prepend(Event r) { prepend(new EventTask(r));}
    public void prepend(int x){ prepend(new SpecialTask(x));}



    public int schedule(ChallengeDriver cd, Game g)
    {
        Task t = mStart;
        mLastTask=t;
        if(t!=null)
        {
            mStart=mStart.next();
            mLastTask.mNext=null;
            //Log.e("___SCHEDULER_DEBUG___", "Executing task : "+t.toString());
            return t.exec(this, cd, g);
        }else  mLastTask.mNext=null;
        return Task.TASK_NONE;
    }

    public ArrayList<Task> getTaskList()
    {
        ArrayList<Task> at = new ArrayList<Task>();
        for(Task t=mStart; t!=null ;t=mStart.next())
            at.add(t);
        return at;
    }

    public Task getLastTask() {
        return mLastTask;
    }

    public Task getStart() {
        return mStart;
    }

    private void prepend(Task t)
    {
        Task sec = mStart;
        mStart=t;
        mStart.end().mNext=sec;
        Log.e("___", "ok");
    }

    public void clear()
    {
        mStart=null;
    }

    public void undo()
    {
        if(mLastTask!=null)
        {
            prepend(mLastTask);
            mLastTask=null;
        }
    }
}
