package com.ffii.fpsms.modules.master.service

import com.ffii.fpsms.modules.master.entity.ItemUom
import com.ffii.fpsms.modules.master.entity.ItemUomRespository
import com.ffii.fpsms.modules.master.web.models.ItemUomRequest
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.io.IOException
import kotlin.jvm.optionals.getOrNull

@Service
open class ItemUomService(
    val itemsService: ItemsService,
    val uomConversionService: UomConversionService,
    val itemUomRespository: ItemUomRespository,
    val currencyService: CurrencyService
) {
    open fun findAllByItemsId(itemId: Long): List<ItemUom> {
        return itemUomRespository.findAllByItemIdAndDeletedIsFalse(itemId);
    }

    open fun findById(id: Long): ItemUom? {
        return itemUomRespository.findByIdAndDeletedIsFalse(id);
    }

    open fun findByM18Id(m18Id: Long): ItemUom? {
        return itemUomRespository.findByM18IdAndDeletedIsFalse(m18Id);
    }

    open fun findPurchaseUnitByItemId(itemId: Long): ItemUom? {
        return itemUomRespository.findByItemIdAndPurchaseUnitIsTrueAndDeletedIsFalse(itemId)
    }

    open fun findPurchaseUnitByM18ItemId(m18ItemId: Long): ItemUom? {
        return itemUomRespository.findByItemM18IdAndPurchaseUnitIsTrueAndDeletedIsFalse(m18ItemId)
    }

    // See if need to update the response
    open fun saveItemUom(request: ItemUomRequest): ItemUom {
        val itemUom = request.m18Id?.let { findByM18Id(it) } ?: request.id?.let { findById(it) } ?: ItemUom()
        if (request.m18LastModifyDate == itemUom.m18LastModifyDate) {
            return itemUom
        }

        val item = request.itemId?.let { itemsService.find(it).getOrNull() }
        val uom = request.m18UomId?.let { uomConversionService.findByM18Id(it) } ?: request.uomId?.let { uomConversionService.find(it).getOrNull() }
        val currency = request.currencyId?.let { currencyService.findById(it) }

        itemUom.apply {
            this.uom = uom
            this.item = item
            this.currency = currency
            baseUnit = request.baseUnit
            stockUnit = request.stockUnit
            pickingUnit = request.pickingUnit
            salesUnit = request.salesUnit
            purchaseUnit = request.purchaseUnit
            price = request.price
            m18Id = request.m18Id
            m18LastModifyDate = request.m18LastModifyDate
        }

        val savedItemUom = itemUomRespository.saveAndFlush(itemUom)

        return savedItemUom
    }

    @Throws(IOException::class)
    @Transactional
    open fun deleteItemUoms(deleteIds: List<Long>) {
//        println(deleteIds)
        if (deleteIds.isNotEmpty()) {
            itemUomRespository.deleteAllByIdIn(deleteIds)
        }
    }
}