package com.develop.step.viewmodel

import android.app.Application
import android.graphics.Color
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import com.develop.food.base.data.model.CookSettingType
import com.develop.food.base.repo.FoodDataProvider
import com.develop.food.base.repo.entity.DevRecipe
import com.develop.food.base.repo.entity.DevRecipeCookingStep
import com.develop.step.model.CookStatus
import com.kuyuntech.cofarcooking.device.sdk.constant.core.DevStatus
import java.util.Objects
import java.util.concurrent.CopyOnWriteArrayList

class CookStepViewModel(application: Application) : AndroidViewModel(application) {

    @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())
            }

            val stepStatus = CookStepStatus("FINISH_DESC",DevRecipeCookingStep());
            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) {
        stepIndex = index
        allSteps.getOrNull(stepIndex)?.let {
            if (stepDisplay.value != it) {
                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()?.source?.code == cookingStep?.source?.code
    }

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

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

}