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

import com.capgemini.framework.common.StringHelper;
import com.capgemini.reports.bomlineholder.BOMLineHolder;
import com.capgemini.reports.definition.r07report.data.filter.comparators.generics.GenericBLComparator;
import com.capgemini.reports.definition.r07report.data.filter.comparators.part.PartBLComparator;
import com.capgemini.reports.exceptions.NotSupportedException;
import com.capgemini.reports.snecmaobjects.ISnecmaObject;

import java.io.Serializable;
import java.util.Comparator;

/**
 * Helper class to comapre two {@link BOMLineHolder}s content.
 */
public abstract class AbstractBomLineComparator implements Comparator<BOMLineHolder>, Serializable {
    private static final long serialVersionUID = 3764547367272622769L;

    private static int mySafeCmp(final String str1, final String str2) {
        if (str1 == null) {
            return str2 == null ? 0 : 1;
        } else if (str2 == null) {
            return -1;
        } else {
            return str1.compareTo(str2);
        }
    }

    /**
     * Compares two Receptors together. Only their item ID and Name are compared.
     *
     * @param thisBL  this object
     * @param otherBL an other object
     * @return the diff
     */
    public static int compareReceptors(final BOMLineHolder thisBL, final BOMLineHolder otherBL) {
        ISnecmaObject thisReceptor = thisBL.getSnecmaObject();
        ISnecmaObject otherReceptor = otherBL.getSnecmaObject();
        return AbstractItemComparator.compareReceptors(thisReceptor, otherReceptor);
    }

    /**
     * Compares two components's contents. The components can be any Part or any Generic.
     *
     * @param thisBL  this object
     * @param otherBL an other object
     * @return the diff
     * @throws NotSupportedException if the objects are of the wrong type
     */
    public static int compareComponents(final BOMLineHolder thisBL, final BOMLineHolder otherBL) throws NotSupportedException {
        ISnecmaObject thisComponent = thisBL.getSnecmaObject();
        ISnecmaObject otherComponent = otherBL.getSnecmaObject();
        String thisType = thisComponent.getType();
        String otherType = otherComponent.getType();
        int cmp = thisType.compareTo(otherType);
        if (cmp != 0) {
            return cmp;
        }
        if (thisComponent.isGeneric()) {
            return GenericBLComparator.compareGenerics(thisBL, otherBL);
        }
        if (thisComponent.isPart()) {
            return PartBLComparator.compareParts(thisBL, otherBL);
        } else {
            throw new NotSupportedException(
                    StringHelper.concat("Unsupported Component type: ", thisComponent.getItemId(), " of type ", thisType).toString());
        }
    }

    protected int safeCmp(final String str1, final String str2) {
        return mySafeCmp(str1, str2);
    }
}
