package com.adealink.weparty.order.manager

import com.adealink.frame.base.Rlt
import com.adealink.frame.frame.BaseFrame
import com.adealink.weparty.App
import com.adealink.weparty.module.order.data.OrderDiscountInfo
import com.adealink.weparty.module.order.data.discountLD
import com.adealink.weparty.module.order.listener.IDiscountListener
import com.adealink.weparty.order.data.OrderDiscountData
import com.adealink.weparty.order.datasource.remote.OrderHttpService
import kotlinx.coroutines.launch

val discountManager: IDiscountManager by lazy { DiscountManger() }

class DiscountManger : BaseFrame<IDiscountListener>(), IDiscountManager {

    private var discountInfo: OrderDiscountInfo? = null

    private val orderHttpService by lazy {
        App.instance.networkService.getHttpService(OrderHttpService::class.java)
    }

    override fun queryDiscountInfo() {
        launch {
            suspendQueryDiscountInfo()
        }
    }

    override suspend fun suspendQueryDiscountInfo(): Rlt<Any> {
        val rlt = orderHttpService.orderDiscount()
        when (rlt) {
            is Rlt.Failed -> {
                //Ntd.
                updateDisCountInfo(null)
            }

            is Rlt.Success -> {
                updateDisCountInfo(rlt.data.data)
            }
        }
        return rlt
    }

    private fun updateDisCountInfo(data: OrderDiscountData?) {
        if (data == null) {
            discountInfo = null
            notifyDiscountChanged()
            return
        }
        discountInfo = OrderDiscountInfo(
            data.hasDiscount,
            data.discountRate,
            data.price
        )
        notifyDiscountChanged()
    }

    override fun getDiscountInfo(): OrderDiscountInfo? {
        return discountInfo
    }

    override fun clear() {
        super.clear()
        discountInfo = null
        notifyDiscountChanged()
    }

    private fun notifyDiscountChanged() {
        discountLD.postValue(discountInfo)
    }
}