package but.androidstudio.tetris

import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorManager
import android.media.MediaPlayer
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.core.content.ContextCompat.getSystemService
import modele.Game
import views.ViewsGame

class GameFragment : Fragment(){

    private val heightGame:Int = 15 // Line number
    private val withGame:Int = 7 // Column number
    private lateinit var viewGame:ViewsGame
    private lateinit var modeleGame:Game

    private lateinit var sensorManager: SensorManager

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_game, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        viewGame = view.findViewById<ViewsGame>(R.id.tabGame)
        viewGame.nbCaseHauteur = heightGame
        viewGame.nbCaseLargeur = withGame

        val sensorManager = activity?.getSystemService(Context.SENSOR_SERVICE) as SensorManager
        val sensor: Sensor? = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR)

        val mediaPlayer = MediaPlayer.create(context,R.raw.tetris)
        val buttonRight:Button = view.findViewById(R.id.Button_Right)
        val buttonLeft:Button = view.findViewById(R.id.Button_Left)
        val buttonRotateRight:Button = view.findViewById(R.id.Button_Right_Rotation)
        val buttonRotateLeft:Button = view.findViewById(R.id.Button_Left_Rotation)
        val points:TextView = view.findViewById(R.id.Id_Points)

        modeleGame = Game(height = heightGame, width = withGame, viewGame = viewGame, points = points)

        buttonRight.setOnClickListener {
            modeleGame.dashBoard.moveRight(modeleGame.currentShape)
        }
        buttonLeft.setOnClickListener {
            modeleGame.dashBoard.moveLeft(modeleGame.currentShape)
        }
        buttonRotateRight.setOnClickListener {
            modeleGame.dashBoard.rotateShapeRight(modeleGame.currentShape)
        }
        buttonRotateLeft.setOnClickListener {
            modeleGame.dashBoard.rotateShapeLeft(modeleGame.currentShape)
        }

        mediaPlayer.start()
        modeleGame.startGame()
    }

}