/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package eleph.android.games.gamin;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import eleph.android.games.gamin.model.GaminModel;

/**
 *
 * @author eleph
 */
public class GameView extends SurfaceView
        implements SurfaceHolder.Callback {

  TheApplication app;
  Paint paint = new Paint();
  int canvasWidth;
  int cellSize;

  public GameView(Context context, AttributeSet attrs) {

    super(context, attrs);

    getHolder().addCallback(this);

    getApp(context);

  }

  public GameView(Context context) {

    super(context);

    getHolder().addCallback(this);

    this.getApp(context);

  }
  
  public void surfaceCreated(SurfaceHolder holder) {
  }

  public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    canvasWidth = width;
    cellSize = width/3; // ATTENTION: conatante
    reDraw();
  }

  public void surfaceDestroyed(SurfaceHolder arg0) {
   }

  @Override
  public boolean onTouchEvent(MotionEvent event) {

    int x = (int) event.getX();
    int y = (int) event.getY();
    int action = event.getAction();

    GaminModel theGame = app.getGame();

    switch (action) {
      case MotionEvent.ACTION_DOWN: {
        return theGame.actionSelect(x/cellSize, y/cellSize);
      }
      case MotionEvent.ACTION_MOVE: {
        return true;
      }
      case MotionEvent.ACTION_UP: {
        boolean r = theGame.actionSwap(x/cellSize, y/cellSize);
        if (r) reDraw();
        return r;
      }
      default:
        return false;
    }

  }

  void reDraw() {
    Canvas c = getHolder().lockCanvas();
    if (c != null) {
      this.onDraw(c);
      getHolder().unlockCanvasAndPost(c);
    }
  }

  @Override
  public void onDraw(Canvas canvas) {

    paint.reset();
    GaminModel theGame = app.getGame();
    
    if (theGame.isAchieved())
      canvas.drawColor(Color.YELLOW);
    else
      canvas.drawColor(Color.GRAY);

    paint.setColor(Color.BLACK);
    for (int x = 0; x < canvasWidth; x += cellSize) {
      canvas.drawLine(x, 0, x, canvasWidth, paint);
    }
    for (int y = 0; y < canvasWidth; y += cellSize) {
      canvas.drawLine(0, y, canvasWidth, y, paint);
    }

    paint.setTextSize(50); // Constante
    paint.setFlags(Paint.ANTI_ALIAS_FLAG);
    for (int x = 0; x < 3; x++) {
      for (int y = 0; y < 3; y++) {
        canvas.drawText(Integer.toString(theGame.get(x, y)), 
                        (x * cellSize) + 11, 
                        (cellSize + y * cellSize) - 6,
                        paint);
      }
    }
  }

  final void getApp(Context context) {
    app = (TheApplication) (context.getApplicationContext());
  }

}
