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.InventoryCatalog;
import com.ecep.contract.service.InventoryCatalogService;
import com.ecep.contract.service.InventoryService;

import lombok.NoArgsConstructor;

@NoArgsConstructor
public class InventoryTableCell<V> extends AsyncUpdateTableCell<V, Inventory> {

    private InventoryCatalogService inventoryCatalogService;

    public InventoryTableCell(InventoryService service) {
        setService(service);
    }

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

    @Override
    public String format(Inventory entity) {
        InventoryCatalog catalog = entity.getCatalog();
        return (catalog != null ? (catalog.getName() + " ") : "") + entity.toPrettyString();
    }

    @Override
    protected boolean isInitialized(Inventory proxy) {
        if (!super.isInitialized(proxy)) {
            return false;
        }
        InventoryCatalog catalog = proxy.getCatalog();
        if (catalog != null) {
            return ProxyUtils.isInitialized(catalog);
        }
        return true;
    }

    @Override
    protected Inventory initialize() {
        Inventory inventory = super.initialize();
        InventoryCatalog catalog = inventory.getCatalog();
        if (catalog != null && !ProxyUtils.isInitialized(catalog)) {
            catalog = getInventoryCatalogService().findById(catalog.getId());
            inventory.setCatalog(catalog);
        }
        return inventory;
    }
}
