package com.agineek.agineek_pad_plugin

import android.util.Log
import android.util.Pair
import androidx.annotation.NonNull
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.locks.ReentrantLock
import kotlin.collections.ArrayList

@kotlin.ExperimentalStdlibApi
class Player(
    public var id: String,
    public var hitColor: String
) : MethodCallHandler {
    companion object {
        @JvmStatic private val Tag = "Player"
    }
    public var hitCount: Int = 0
    public var missCount: Int = 0
    public var totalCount: Int = 0
        get() = hitCount + missCount
    public var totalPoints: Int = 0
    public var hitPercentage: Double = 0.0
        get() = hitCount * 1.0 / totalCount
    public var missPercentage: Double = 0.0
        get() = missCount * 1.0 / totalCount
    private val hitSequence: ArrayList<String> = ArrayList<String>()
    private val padHits: ConcurrentHashMap<String, Integer> = ConcurrentHashMap<String, Integer>()
    private val padMisses: ConcurrentHashMap<String, Integer> = ConcurrentHashMap<String, Integer>()
    private val lock = ReentrantLock()

    public override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
        val args = call.arguments<ArrayList<*>>()

        when (call.method) {
            else -> {
                result.notImplemented()
            }
        }
    }

    public fun reset() {
        totalCount = 0
        hitCount = 0
        missCount = 0
        totalPoints = 0
    }

    public fun addHit(currentTime: Long, padId: String) {
        lock.lock()
        hitCount++
        Log.d(Tag, "Took $currentTime")
        hitSequence.add("$padId:${(currentTime / 1000.0)},1")
        lock.unlock()
    }

    public fun addMiss(currentTime: Long, padId: String) {
        lock.lock()
        missCount++
        hitSequence.add("$padId:${(currentTime / 1000.0)},-1")
        lock.unlock()
    }

    public fun wrongHit(currentTime: Long, padId: String) {
        lock.lock()
        missCount++
        hitSequence.add("$padId:${(currentTime / 1000.0)},0")
        lock.unlock()
    }

    public fun addPoints() {
        totalPoints += 5
    }

    public fun removePoints() {
        totalPoints -= 2
    }
}
