package com.hyperling.apps.games;

import android.graphics.Canvas;
import android.util.Log;
import android.view.SurfaceHolder;

/**
 * Created by ling on 12/17/16.
 */

public class GameLoopThread extends Thread {
    private final int FPS = 30;
    protected double averageFPS;
    private SurfaceHolder surfaceHolder;
    private GameView gameView;
    private boolean running;
    public static Canvas canvas;

    public boolean markerFrame;

    private String TAG;

    public GameLoopThread(SurfaceHolder sh, GameView gv){
        super();
        surfaceHolder = sh;
        gameView = gv;

        TAG = gameView.getResources().getString(R.string.TAG);

        markerFrame = false;
    }

    @Override
    public void run() {
        super.run();

        long timeStart, timeRun, timeWait, timeTotal, timeTarget;
        timeTotal = 0;
        timeTarget = 1000/FPS;

        int frameCount = 0;

        while(running){
            timeStart = System.currentTimeMillis();
            canvas = null;

            try{
                canvas = this.surfaceHolder.lockCanvas();
                synchronized (surfaceHolder){
                    this.gameView.update();
                    this.gameView.draw(canvas);
                }
            } catch(Exception e){
                e.printStackTrace();
            } finally {
                if (canvas != null) {
                    try {
                        surfaceHolder.unlockCanvasAndPost(canvas);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            timeRun = (System.currentTimeMillis() - timeStart);
            timeWait = timeTarget - timeRun;

            if (timeWait > 0) {
                try {
                    this.sleep(timeWait);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            timeTotal += System.currentTimeMillis()-timeStart;
            frameCount++;
            if (frameCount >= FPS){
                averageFPS = 1000/((timeTotal/frameCount));
                frameCount = 0;
                timeTotal = 0;

                Log.i(TAG, "GameLoopThread.run():  averageFPS=" + averageFPS);
                Log.d(TAG, "GameLoopThread.run():  canvas.getHeight()=" + canvas.getHeight() + ", canvas.getWidth()=" + canvas.getWidth());

                markerFrame = true;
            }
            else{
                markerFrame = false;
            }
        }
    }

    public void setRunning(boolean r){
        running = r;

        if (running) {
            this.start();
        }
    }
}
