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

import com.ecep.contract.SpringApp;
import com.ecep.contract.service.CompanyService;
import com.ecep.contract.service.VendorService;
import com.ecep.contract.service.IEntityService;
import com.ecep.contract.vo.VendorVo;
import com.ecep.contract.vo.CompanyVo;

import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.Callback;
import lombok.NoArgsConstructor;
import lombok.Setter;

@NoArgsConstructor
public class CompanyVendorTableCell<T> extends AsyncUpdateTableCell<T, Integer, VendorVo> {
    public static <S> Callback<TableColumn<S, Integer>, TableCell<S, Integer>> forTableColumn() {
        return forTableColumn(SpringApp.getBean(VendorService.class));
    }

    public static <S> Callback<TableColumn<S, Integer>, TableCell<S, Integer>> forTableColumn(
            VendorService sevice) {
        CompanyService companyService = SpringApp.getBean(CompanyService.class);
        return param -> new CompanyVendorTableCell<S>(sevice, companyService);
    }

    @Setter
    private CompanyService companyService;

    public CompanyVendorTableCell(VendorService service, CompanyService companyService) {
        setService(service);
        setCompanyService(companyService);
    }

    @Override
    protected IEntityService<VendorVo> getServiceBean() {
        return SpringApp.getBean(VendorService.class);
    }

    protected CompanyService getCompanyService() {
        if (companyService == null) {
            companyService = SpringApp.getBean(CompanyService.class);
        }
        return companyService;
    }

    @Override
    protected boolean isInitialized(VendorVo proxy) {
        if (!super.isInitialized(proxy)) {
            return false;
        }
        return false;
    }

    @Override
    protected VendorVo initialize() {
        VendorVo vendor = super.initialize();
        return vendor;
    }

    @Override
    public String format(VendorVo vendor) {
        Integer companyId = vendor.getCompanyId();
        CompanyVo company = getCompanyService().findById(companyId);
        if (company == null) {
            return "#" + vendor.getId() + " -";
        }
        return toString(company);
    }
}
