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

import com.ecep.contract.util.ProxyUtils;

import com.ecep.contract.SpringApp;
import com.ecep.contract.model.Company;
import com.ecep.contract.model.CompanyVendor;
import com.ecep.contract.service.CompanyService;
import com.ecep.contract.service.CompanyVendorService;
import com.ecep.contract.service.IEntityService;

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, CompanyVendor> {
    public static <S> Callback<TableColumn<S, CompanyVendor>, TableCell<S, CompanyVendor>> forTableColumn() {
        return forTableColumn(SpringApp.getBean(CompanyVendorService.class));
    }

    public static <S> Callback<TableColumn<S, CompanyVendor>, TableCell<S, CompanyVendor>> 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<CompanyVendor> getServiceBean() {
        return SpringApp.getBean(CompanyVendorService.class);
    }

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

    @Override
    protected boolean isInitialized(CompanyVendor proxy) {
        if (!super.isInitialized(proxy)) {
            return false;
        }
        Company company = proxy.getCompany();
        if (company != null) {
            return ProxyUtils.isInitialized(company);
        }
        return true;
    }

    @Override
    protected CompanyVendor initialize() {
        CompanyVendor vendor = super.initialize();
        Company company = vendor.getCompany();
        if (company != null && !ProxyUtils.isInitialized(company)) {
            company = getCompanyService().findById(company.getId());
            vendor.setCompany(company);
        }
        return vendor;
    }

    @Override
    public String format(CompanyVendor vendor) {
        Company company = vendor.getCompany();
        if (company == null) {
            return "#" + vendor.getId() + " -";
        }
        return toString(company);
    }
}
