package com.example.variableaxlemonitor.viewmodel

import android.app.Application
import android.bluetooth.BluetoothDevice
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.example.variableaxlemonitor.bluetooth.BluetoothManager
import com.example.variableaxlemonitor.data.AxleData
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.launch

class AxleViewModel(application: Application) : AndroidViewModel(application) {
    private val bluetoothManager = BluetoothManager(application)

    val isConnected: StateFlow<Boolean> = bluetoothManager.isConnected
    val lastMessage: StateFlow<String> = bluetoothManager.lastMessage
    val mtu: StateFlow<Int> = bluetoothManager.mtu
    val axleData: StateFlow<AxleData> = bluetoothManager.axleData
    
    val dataReceivedTrigger: SharedFlow<Unit> = bluetoothManager.dataReceivedTrigger

    val foundDevices: StateFlow<List<BluetoothDevice>> = bluetoothManager.foundDevices

    private val _loginError = MutableSharedFlow<String>()
    val loginError: SharedFlow<String> = _loginError.asSharedFlow()

    private val _loginSuccess = mutableStateOf(false)
    val loginSuccess: State<Boolean> = _loginSuccess

    fun login(user: String, pass: String) {
        if (user == "mms" && pass == "mms") {
            _loginSuccess.value = true
        } else {
            viewModelScope.launch {
                _loginError.emit("User/Password가 맞지않습니다. 다시 시도하십시오.")
            }
        }
    }

    fun startScan() {
        bluetoothManager.startScan()
    }

    fun stopScan() {
        bluetoothManager.stopScan()
    }

    fun connectToDevice(device: BluetoothDevice) {
        bluetoothManager.connect(device)
    }

    fun disconnect() {
        bluetoothManager.disconnect()
    }
}
