package hello;

import javax.microedition.lcdui.game.*;
import javax.microedition.lcdui.*;
import java.io.IOException;

public class Canvas extends GameCanvas implements Runnable
{
    private int sleepTime = 30;
    private Instructions instruct;
    private Tutorial tutorial;
    private GamePlay game;
    private boolean inInstructions = false;
    private boolean inTutorial = false;
    private boolean inGame = true;
    private Background tiledBackground;

    public Canvas()
    {
        super(false);
    }

    public void run()
    {
        while(true)
        {
            update(getGraphics());

            try{
                Thread.sleep(sleepTime);
            } catch (Exception e) {

            }
        }
    }

    public void start()
    {
        instruct = new Instructions(this);
        tutorial = new Tutorial(this);
        game = new GamePlay();

        Thread runner = new Thread(this);
        runner.start();
    }

    private void createBackground(Graphics g)
    {
      if(inInstructions)
      {
           if(tiledBackground == null)
             tiledBackground = new Background(1);
      }
      else if(inTutorial)
      {
          if(tiledBackground == null)
             tiledBackground = new Background(1);
      }
      else if(inGame)
      {
          if(tiledBackground == null)
            tiledBackground = new Background(1);
      }

       if(tiledBackground != null)
        tiledBackground.draw(g);
    }

    public void update(Graphics g)
    {
        createBackground(g);

        if(inInstructions)
        {
            instruct.navigate(this);
            instruct.nextScreen(g, this);
            if(instruct.isFinished())
            {
                inInstructions = false;
                inTutorial = true;
            }
        }
        else if(inTutorial)
        {

            tutorial.runTutorial(this, g);
            if(tutorial.isFinished())
            {
                inTutorial = false;
                inGame = true;
            }
        }
        else if(inGame)
        {
            game.runGamePlay(this, g);
        }

        flushGraphics();
    }

    public Background getBackground()
    {
        return tiledBackground;
    }
}





