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

import com.ecep.contract.SpringApp;
import com.ecep.contract.service.CompanyService;
import com.ecep.contract.service.CompanyVendorService;
import com.ecep.contract.service.IEntityService;
import com.ecep.contract.vo.CompanyVendorVo;
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, CompanyVendorVo> {
    public static <S> Callback<TableColumn<S, Integer>, TableCell<S, Integer>> forTableColumn() {
        return forTableColumn(SpringApp.getBean(CompanyVendorService.class));
    }

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

    @Setter
    private CompanyService companyService;

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

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

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

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

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

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