contract RemoveComponentModule is ModuleBase {

    /* ============ State ============ */

    ISetToken public setToken;
    address public component;
    bool public used;

    /**
     * CONSTRUCTOR: Pass in the setToken intended to be modified and the component being removed.
     *
     * @param _setToken                 Address of SetToken contract
     * @param _component                Address of duplicate token being removed
     */
    constructor(IController _controller, ISetToken _setToken, address _component) public ModuleBase(_controller) {
        setToken = _setToken;
        component = _component;
    }

    /**
     * ONLY MANAGER: Remove stored component from array. Checks to see if there's a duplicate component and
     * that module has not been previously used. Calls remove component which will remove first instance
     * of component in the array and set used to true to make sure removeComponent() cannot be called again.
     */
    function removeComponent() external onlyManagerAndValidSet(setToken) {
        require(!used, "Module has been used");

        address[] memory components = setToken.getComponents();
        uint256 componentCount;
        for (uint256 i = 0; i < components.length; i++) {
            if (component == components[i]) {
                componentCount = componentCount.add(1);
            }
        }
        require(componentCount > 0, "Component does not have duplicate");

        setToken.removeComponent(component);

        used = true;
    }

    /**
     * ONLY MANAGER: Initializes module on the SetToken.
     */
    function initialize()
        external
        onlySetManager(setToken, msg.sender)
        onlyValidAndPendingSet(setToken)
    {
        setToken.initializeModule();
    }

    /**
     * ONLY SET TOKEN: Removes module from SetToken.
     */
    function removeModule() external override {
        require(msg.sender == address(setToken), "Caller must be SetToken");
    }
}
/**
 * @title RemoveComponentModule
 * @author Set Protocol
 *
 * Single use module to remove duplicated component from array.
 */
function initialize()
    external
    onlySetManager(setToken, msg.sender)
    onlyValidAndPendingSet(setToken)
{
    setToken.initializeModule();
}

/**
 * ONLY MANAGER: Initializes module on the SetToken.
 */