package com.pixelmintdrop.game

import android.content.Context
import android.os.Build
import android.os.VibrationEffect
import android.os.Vibrator
import android.os.VibratorManager
import android.view.HapticFeedbackConstants
import android.view.View
import android.util.Log

/**
 * Handles haptic feedback for game events
 */
class GameHaptics(private val context: Context) {

    companion object {
        private const val TAG = "GameHaptics"
    }
    
    // Vibrator service
    private val vibrator: Vibrator = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
        val vibratorManager = context.getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager
        vibratorManager.defaultVibrator
    } else {
        @Suppress("DEPRECATION")
        context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
    }
    
    // Track if gamepad is connected
    private var isGamepadConnected = false
    
    // Set gamepad connection state
    fun setGamepadConnected(connected: Boolean) {
        isGamepadConnected = connected
    }
    
    // Get vibration multiplier based on input method
    private fun getVibrationMultiplier(): Float {
        return if (isGamepadConnected) 1.5f else 1.0f
    }
    
    // Vibrate for line clear (more intense for more lines)
    fun vibrateForLineClear(lineCount: Int) {
        Log.d(TAG, "Attempting to vibrate for $lineCount lines")
        
        // Only proceed if the device has a vibrator and it's available
        if (!vibrator.hasVibrator()) return
        
        // Scale duration and amplitude based on line count and input method
        val multiplier = getVibrationMultiplier()
        val duration = when(lineCount) {
            1 -> (50L * multiplier).toLong()  // Single line: short vibration
            2 -> (80L * multiplier).toLong()  // Double line: slightly longer
            3 -> (120L * multiplier).toLong() // Triple line: even longer
            4 -> (200L * multiplier).toLong() // Quad: longest vibration
            else -> (50L * multiplier).toLong()
        }
        
        val amplitude = when(lineCount) {
            1 -> (80 * multiplier).toInt().coerceAtMost(255)  // Single line: mild vibration
            2 -> (120 * multiplier).toInt().coerceAtMost(255) // Double line: medium vibration
            3 -> (180 * multiplier).toInt().coerceAtMost(255) // Triple line: strong vibration
            4 -> 255 // Quad: maximum vibration
            else -> (80 * multiplier).toInt().coerceAtMost(255)
        }
        
        Log.d(TAG, "Vibration parameters - Duration: ${duration}ms, Amplitude: $amplitude")
        
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                vibrator.vibrate(VibrationEffect.createOneShot(duration, amplitude))
                Log.d(TAG, "Vibration triggered successfully")
            } else {
                @Suppress("DEPRECATION")
                vibrator.vibrate(duration)
                Log.w(TAG, "Device does not support vibration effects (Android < 8.0)")
            }
        } catch (e: Exception) {
            Log.e(TAG, "Error triggering vibration", e)
        }
    }

    fun performHapticFeedback(view: View, feedbackType: Int) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            view.performHapticFeedback(HapticFeedbackConstants.CONFIRM)
        } else {
            @Suppress("DEPRECATION")
            view.performHapticFeedback(feedbackType)
        }
    }

    fun vibrateForPieceLock() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val multiplier = getVibrationMultiplier()
            val duration = (50L * multiplier).toLong()
            val amplitude = (VibrationEffect.DEFAULT_AMPLITUDE * multiplier).toInt().coerceAtMost(255)
            val vibrationEffect = VibrationEffect.createOneShot(duration, amplitude)
            vibrator.vibrate(vibrationEffect)
        }
    }

    fun vibrateForPieceMove() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val multiplier = getVibrationMultiplier()
            val duration = (20L * multiplier).toLong()
            val amplitude = (VibrationEffect.DEFAULT_AMPLITUDE * 0.3 * multiplier).toInt().coerceAtLeast(1).coerceAtMost(255)
            val vibrationEffect = VibrationEffect.createOneShot(duration, amplitude)
            vibrator.vibrate(vibrationEffect)
        }
    }

    fun vibrateForGameOver() {
        Log.d(TAG, "Attempting to vibrate for game over")
        
        // Only proceed if the device has a vibrator and it's available
        if (!vibrator.hasVibrator()) return
        
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val multiplier = getVibrationMultiplier()
                val duration = (300L * multiplier).toLong()
                val amplitude = (VibrationEffect.DEFAULT_AMPLITUDE * multiplier).toInt().coerceAtMost(255)
                val vibrationEffect = VibrationEffect.createOneShot(duration, amplitude)
                vibrator.vibrate(vibrationEffect)
                Log.d(TAG, "Game over vibration triggered successfully")
            } else {
                @Suppress("DEPRECATION")
                vibrator.vibrate(300L)
                Log.w(TAG, "Device does not support vibration effects (Android < 8.0)")
            }
        } catch (e: Exception) {
            Log.e(TAG, "Error triggering game over vibration", e)
        }
    }
} 