#include "tetris-graph.h"

int main(void){
    
    InitGame();
    
    Piece* pieceList = getPiecesData("tetris.data");
    Grid grid = gridInit();
    Piece p = pieceInit();
    bool isFixed = true;

    int frameCounter = 0;
    
    while(!WindowShouldClose() && !gameOver(grid)){

        BeginDrawing();
        InitDisplay();
        
        // Testing
        char text1[10];
        itoa(grid.height, text1, 10);
        DrawText(text1, 20, 20, 20, RED);
        
        char text2[5];
        itoa(height(grid), text2, 10);
        DrawText(text2, 50, 20, 20, RED);
        
        if(!gameOver(grid)){
            DrawText("not game over", 100, 20, 20, RED);
        }
        
        // Nouvelles pièces
        if(isFixed){
            p = generePiece(pieceList);
            movePieceHztl(p, 3);
            isFixed = false;
        }
        
        // Déplacements saisis au clavier
        if(IsKeyPressed(KEY_LEFT) && canMoveHztl(grid, p, -1)){
            movePieceHztl(p, -1);
        }
        if(IsKeyPressed(KEY_RIGHT) && canMoveHztl(grid, p, 1)){
            movePieceHztl(p, 1);
        }
        if(IsKeyPressed(KEY_A)) rotatePiece(p, false);
        if(IsKeyPressed(KEY_Z)) rotatePiece(p, true);

        // Déplacer pièce toutes les 1s
        if(frameCounter%20 == 0){
            if(canMove(p, grid)){
                movePieceVert(p, 1);
            }
            else{
                addPieceToGrid(p, grid);
                isFixed = true;

                removeLinesIfCompleted(grid);
                
            }
        }

        drawPiece(p);
        drawGrid(grid);
        displayGrid(grid);

        frameCounter++;
        
        EndDrawing();
    }
    CloseWindow();
    
    return EXIT_SUCCESS;
}