#include "tetris-graph.h"

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

    int score = 0;

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

        BeginDrawing();
        InitDisplay();
        displayScore(score);
        
        // 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_Q)){    // A en AZERTY
            while(rotateBorderLeft(p, false)){
                movePieceHztl(p, 1);
            }
            while(rotateBorderRight(p, false)){
                movePieceHztl(p, -1);
            }
            while(rotateCollideGrid(grid, p, false)){
                movePieceVert(p, -1);
            }
            
            rotatePiece(grid, p, false);
        } 
        if(IsKeyPressed(KEY_W)){    // Z en AZERTY
            while(rotateBorderLeft(p, true)){
                movePieceHztl(p, 1);
            }
            while(rotateBorderRight(p, true)){
                movePieceHztl(p, -1);
            }
            while(rotateCollideGrid(grid, p, true)){
                movePieceVert(p, -1);
            }

            rotatePiece(grid, 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;

                score += removeLinesIfCompleted(grid);
                
            }
        }

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

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