import java.util.Random;


public class Philosopher extends Thread {
    

    enum STATES {HUNGRY, EATING, THINKING}
    STATES state;
    int id;
    PhilosopherApplet table;
    Random rand;
    boolean sleep;

    public Philosopher(PhilosopherApplet table, int id, boolean sleep){
        state = STATES.HUNGRY;
        this.id = id;
        this.table = table;
        this.sleep = sleep;
        rand = new Random();
    }

    public void run(){
        try {
            while(true){
                state = STATES.HUNGRY;

                //get right chopstick
                table.getFork(id, id);

                //get left chopstick
                table.getFork(id, (id + 1) % table.PHILOSOPHER_COUNT);

                state = STATES.EATING;
                
                //eat
                //sleep(200 + rand.nextInt(800));
                if(sleep)
                    busyRest(rand.nextInt(2) + 1);

                //System.out.println(id + " got to eat!");
                eat++;

                //drop right chopstick
                table.releaseFork(id, id);
                //drop left chopstick
                table.releaseFork(id,  (id + 1) % table.PHILOSOPHER_COUNT);
                
                state = STATES.THINKING;

                //think
                if(sleep)
                    busyRest(rand.nextInt(2) + 1);
                //sleep(200 + rand.nextInt(800));
            }
        }
        catch(InterruptedException ie){
            ie.printStackTrace();
        }
    }

    public String toString(){
        return "Philosopher " + id + " is " + state;
    }

    //rest for t seconds
    public void busyRest(int t){
        int msec = t*1000;

        //get the initial time
        long time = System.currentTimeMillis();
        long endTime = time + msec;

        while(time < endTime){
            time = System.currentTimeMillis();
        }
    }

    //shared variable
    private static int eat = 0;

    public static synchronized int getEat(){
        return eat;
    }

    public static synchronized void incrementEat(){
        eat++;
    }
}