package com.develop.step.viewmodel

import android.graphics.Color
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.util.Log
import androidx.lifecycle.MutableLiveData
import com.develop.base.mvvm.BaseViewModel
import com.develop.common.data_repo.FoodDataProvider
import com.develop.common.data_repo.db.entity.DevRecipe
import com.develop.step.CookSettingType
import com.develop.step.ui.cook_step.model.CookStepStatus
import com.develop.step.ui.cook_step.model.CookStepUiData
import com.develop.step.ui.recipes_detail.model.CookStatus
import com.kuyuntech.cofarcooking.device.sdk.constant.core.DevStatus
import java.util.concurrent.CopyOnWriteArrayList

class CookStepViewModel : BaseViewModel() {

    @Deprecated("后面会移除下面这些CookStatus")
    val tempStatus = CookStatus.Temp(80)
    val timeStatus = CookStatus.Time(5, 0, 0)
    val speedStatus = CookStatus.Speed(2, 0)
    val directionStatus = CookStatus.Direction(1, 1)
    val currentSetting = MutableLiveData(CookSettingType.WEIGHT)
    val stepUiData = CookStepUiData()

    var stepIndex = 0

    // 默认属性, 只读
    val dataCopy = mutableListOf<CookStepUiData>()
    val allSteps = CopyOnWriteArrayList<CookStepStatus>()
    val stepDisplay = MutableLiveData<CookStepStatus>()
    var cookingStep: CookStepStatus? = null
    var recipe: DevRecipe?= null;

    fun queryRecipeCookStep(number: String, currentStepIndex: Int = 0) {
        FoodDataProvider.getDatabase().runInTransaction {
            allSteps.clear()
            recipe =  FoodDataProvider.getDatabase().recipeDao().queryRecipe(number)
            val cookSteps = FoodDataProvider
                .getDatabase()
                .recipeDao()
                .queryCookingStep(number)
            if (cookSteps.isEmpty()) {
                return@runInTransaction
            }
            Log.d("Step", "total count:${cookSteps.size}")
            for (cookStep in cookSteps) {
                val stepStatus = CookStepStatus(
                    cookStep.workMode ?: "", cookStep
                )
                stepStatus.uiData.applyRecipeSetting(cookStep)
                allSteps.add(stepStatus)
                dataCopy.add(stepStatus.uiData.newCopy())
            }
            stepIndex = currentStepIndex
            if (allSteps.isNotEmpty() && allSteps.size > currentStepIndex) {
                allSteps[currentStepIndex].let {
                    stepDisplay.value = it
                    cookingStep = it
                }
            }
        }
    }

    fun nextStep() {
        if (stepIndex >= allSteps.size - 1) {
            return
        }
        stepIndex++
        allSteps.getOrNull(stepIndex)?.let {
            stepDisplay.value = it
        }
    }

    fun prevStep() {
        if (stepIndex <= 0) {
            return
        }
        stepIndex--
        allSteps.getOrNull(stepIndex)?.let {
            stepDisplay.value = it
        }
    }

    fun setDisplayStep(index: Int, force: Boolean = false) {
        stepIndex = index
        allSteps.getOrNull(stepIndex)?.let {
            if (stepDisplay.value != it || force) {
                stepDisplay.value = it
            }
        }
    }

    fun getStepCount(): Int {
        return allSteps.size
    }

    fun isFirstStep(step: CookStepStatus): Boolean {
        return allSteps.indexOf(step) == 0
    }

    fun isFinalStep(step: CookStepStatus): Boolean {
        return allSteps.indexOf(step) == allSteps.size - 1
    }

    fun changeStep(step: CookSettingType) {
        currentSetting.value = step
    }

    fun getNextStep(step: CookStepStatus): CookStepStatus? {
        val index = allSteps.indexOf(step)
        if (index < 0) {
            return null
        }
        return allSteps.getOrNull(index + 1)
    }

    fun setTargetCookingStep(cookStep: CookStepStatus) {
        val stepIndex = allSteps.indexOf(cookStep)
        if (stepIndex < 0) {
            return
        }
        cookStep.hasComplete = false
        cookStep.hasStarted = false
        cookingStep = cookStep
        setDisplayStep(stepIndex)
    }

    fun displayStep(): CookStepStatus? {
        return stepDisplay.value
    }

    fun isCurrentOnCookingStep(): Boolean {
        return displayStep() == cookingStep
    }

    fun isCookingStepStarted(): Boolean {
        return cookingStep != null && cookingStep?.uiData?.runningStatus != DevStatus.STOP.toInt()
    }

    fun getStepCombineText(): CharSequence {
        val spanBuilder = SpannableStringBuilder()
        for (step in allSteps) {
            val description = step.source.description ?: ""
            if (step == displayStep()) {
                spanBuilder.append(
                    description,
                    ForegroundColorSpan(Color.parseColor("#E60012")),
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                )
            } else {
                spanBuilder.append(description)
            }
            spanBuilder.append("\n\n")
        }
        return spanBuilder
    }
}