/*
 * Copyright (c) 2017 XMLmind Software. All rights reserved.
 *
 * Author: Hussein Shafie
 *
 * This file is part of the XMLmind Assembly Processor project.
 * For conditions of distribution and use, see the accompanying legal.txt file.
 */
package com.xmlmind.assembly;

import java.util.Arrays;
import org.w3c.dom.Element;
import com.xmlmind.util.ObjectUtil;
import com.xmlmind.util.ArrayUtil;

/**
 * <b>Not part of the public, documented, API:</b> representation of element
 * <code>&lt;relationship&gt;</code>.
 */
@SuppressWarnings("overrides")
public final class Relationship {
    public Element source;
    public String type; // May be null.
    public String association; // May be empty; not null.
    public Instance[] instances;

    // -----------------------------------------------------------------------

    public Relationship() {
        this(null);
    }

    public Relationship(Element source) {
        this.source = source;
        association = "";
        instances = Instance.EMPTY_LIST;
    }

    @Override
    public boolean equals(Object other) {
        if (other == null || !(other instanceof Relationship)) {
            return false;
        }

        Relationship o = (Relationship) other;
        return (ObjectUtil.equals(type, o.type) &&
                ObjectUtil.equals(association, o.association) &&
                Arrays.equals(instances, o.instances));
    }

    public boolean contains(Instance instance) {
        return (indexOfInstance(instances, instance) >= 0);
    }

    public void add(Instance instance) {
        int index = indexOfInstance(instances, instance);
        if (index >= 0) {
            instances = ArrayUtil.removeAt(instances, index);
        }
        instances = ArrayUtil.append(instances, instance);
    }

    public static int indexOfInstance(Instance[] instances, Instance instance) {
        final String resourceId = instance.resourceId;
        final int count = instances.length;
        for (int i = 0; i < count; ++i) {
            // Do not consider linking.
            if (instances[i].resourceId.equals(resourceId)) {
                return i;
            }
        }

        return -1;
    }
}

