package com.capgemini.reports.definition.r07report.data.filter.comparators.rf;

import com.capgemini.reports.bomlineholder.BOMLineHolder;
import com.capgemini.reports.bomlineholder.BOMLineHolderHelper;
import com.capgemini.reports.exceptions.InvalidInputException;
import com.capgemini.reports.exceptions.NotFoundException;
import com.capgemini.reports.snecmaobjects.admin.RFAdminARevision;
import com.capgemini.reports.snecmaobjects.rf.AbstractRF;
import lombok.extern.slf4j.Slf4j;

/**
 * Compares two RFPartAssembs together.
 */
@Slf4j
public class RfPartAssembComparator extends RfComparator {

    private static final long serialVersionUID = -9166209208947984853L;

    RfPartAssembComparator() {
    }

    @Override
    public int compare(final BOMLineHolder thisRfBL, final BOMLineHolder otherRfBL) {
        // Compare part data
        AbstractRF thisRf = (AbstractRF) thisRfBL.getSnecmaObject();
        AbstractRF otherRf = (AbstractRF) otherRfBL.getSnecmaObject();
        int cmp = thisRf.getName().compareTo(otherRf.getName());
        if (cmp != 0) {
            return cmp;
        }

        // Bowse children for RF Admin A
        return compareRfAdminA(thisRfBL, otherRfBL);
    }

    private int compareRfAdminA(final BOMLineHolder thisRfBL, final BOMLineHolder otherRfBL) {
        // Bowse children for RF Admin A
        RFAdminARevision thisRfAdminAP = getRfAdminA(thisRfBL);
        RFAdminARevision otherRfAdminAP = getRfAdminA(otherRfBL);

        if (thisRfAdminAP == null || otherRfAdminAP == null) {
            if (thisRfAdminAP == null && otherRfAdminAP == null) {
                log.warn("No RF Admin AP found below both compared RF Parts: " + thisRfBL.getSnecmaObject().getName() + " / "
                        + otherRfBL.getSnecmaObject().getName());
                // No difference, then!
                return 0;
            } else {
                log.warn("No RF Admin AP found below one of the compared RF Parts: " + thisRfBL.getSnecmaObject().getName() + " / "
                        + otherRfBL.getSnecmaObject().getName());
                return 1; // Diff found
            }
        }
        int cmp = safeCmp(thisRfAdminAP.getSuiviMontage(), otherRfAdminAP.getSuiviMontage());
        if (cmp == 0) {
            cmp = safeCmp(thisRfAdminAP.getResponsableRepere(), otherRfAdminAP.getResponsableRepere());
        }
        return cmp;
    }

    private RFAdminARevision getRfAdminA(final BOMLineHolder thisRfBL) {
        try {
            return BOMLineHolderHelper.findRfAdminA(thisRfBL);
        } catch (NotFoundException | InvalidInputException nfe) {
            log.warn("No RF Admin AP found below: " + thisRfBL.getSnecmaObject().getName(), nfe);
            return null;
        }
    }
}
