package modele

import android.util.Log
import android.widget.TextView
import kotlinx.coroutines.*
import views.ViewsGame
import kotlin.random.Random

class Game(private val width: Int,private val height: Int,private val viewGame:ViewsGame,private val points:TextView,private val difficulty: Difficulty ) {
    val dashBoard: DashBoard = DashBoard(width,height,viewGame)
    lateinit var currentShape: Shape

    //To get the next shape
    private fun getNextShape(): TypeShape {
        return when(Random.nextInt(1,7)){
            1 -> TypeShape(EnumTypeShape.IShape)
            2 -> TypeShape(EnumTypeShape.SquareShape)
            3 -> TypeShape(EnumTypeShape.JShape)
            4 -> TypeShape(EnumTypeShape.LShape)
            5 -> TypeShape(EnumTypeShape.SShape)
            6 -> TypeShape(EnumTypeShape.TShape)
            7 -> TypeShape(EnumTypeShape.ZShape)
            else -> throw Exception("Problème de random getNextShape()")
        }
    }


    // The start game function
    fun startGame(){
        currentShape = Shape(getNextShape(),Position(width/2,0))
        dashBoard.addShape(currentShape)

        dashBoard.updateViewGame()

        // Ne pas utiliser de global scope !!!!
        GlobalScope.launch {
            while(true){
                if(dashBoard.fallingShape(currentShape,difficulty)){

                    // Clear line
                    val nbLine = dashBoard.clearLines()

                    // Score
                    if ( (nbLine > 0) and (nbLine<4)){
                        val tmpPoints:String = points.text as String
                        points.text = (tmpPoints.toInt()+(nbLine*100)).toString()
                    }
                    if ( nbLine == 4 ){
                        val tmpPoints:String = points.text as String
                        points.text = (tmpPoints.toInt()+1200).toString()
                    }
                }
                else {
                    // New shape
                    currentShape = Shape(getNextShape(),Position(width/2,0))
                    if ( !dashBoard.addShape(currentShape)){
                        break
                    }
                }
            }
            Log.println(Log.INFO,"Status","GAME END !!")
        }
    }
}