package com.ecep.contract.controller.table.cell;

import com.ecep.contract.util.ProxyUtils;

import com.ecep.contract.SpringApp;
import com.ecep.contract.model.Inventory;
import com.ecep.contract.model.PurchaseOrderItem;
import com.ecep.contract.service.InventoryCatalogService;
import com.ecep.contract.service.InventoryService;
import com.ecep.contract.service.PurchaseOrderItemService;
import com.ecep.contract.service.PurchaseOrdersService;

import lombok.NoArgsConstructor;

@NoArgsConstructor
public class PurchaseOrderItemTableCell<V> extends AsyncUpdateTableCell<V, PurchaseOrderItem> {
    PurchaseOrdersService service;
    private InventoryService inventoryService;
    private InventoryCatalogService inventoryCatalogService;

    public PurchaseOrderItemTableCell(PurchaseOrderItemService service) {
        setService(service);
    }

    InventoryService getInventoryService() {
        if (inventoryService == null) {
            inventoryService = SpringApp.getBean(InventoryService.class);
        }
        return inventoryService;
    }

    InventoryCatalogService getInventoryCatalogService() {
        if (inventoryCatalogService == null) {
            inventoryCatalogService = SpringApp.getBean(InventoryCatalogService.class);
        }
        return inventoryCatalogService;
    }

    PurchaseOrdersService getPurchaseOrdersService() {
        if (service == null)
            service = SpringApp.getBean(PurchaseOrdersService.class);
        return service;
    }

    @Override
    protected boolean isInitialized(PurchaseOrderItem orderItem) {
        if (!super.isInitialized(orderItem)) {
            return false;
        }
        Inventory inventory = orderItem.getInventory();
        if (inventory != null) {
            return ProxyUtils.isInitialized(inventory);
        }
        return true;
    }

    @Override
    protected PurchaseOrderItem initialize() {
        PurchaseOrderItem orderItem = super.initialize();
        Inventory inventory = orderItem.getInventory();
        if (inventory != null && !ProxyUtils.isInitialized(inventory)) {
            inventory = getInventoryService().findById(inventory.getId());
            orderItem.setInventory(inventory);
        }
        return orderItem;
    }

    @Override
    public String format(PurchaseOrderItem orderItem) {
        Inventory inventory = orderItem.getInventory();
        return (inventory != null ? (inventory.toPrettyString() + " x ") : "") + orderItem.getQuantity();
    }
}
