contract PhasedEscrow is Ownable {
    using SafeERC20 for IERC20;

    event BeneficiaryUpdated(address beneficiary);
    event TokensWithdrawn(address beneficiary, uint256 amount);

    IERC20 public token;
    IBeneficiaryContract public beneficiary;

    constructor(IERC20 _token) public {
        token = _token;
    }

    /// @notice Funds the escrow by transferring all of the approved tokens
    ///         to the escrow.
    function receiveApproval(
        address _from,
        uint256 _value,
        address _token,
        bytes memory
    ) public {
        require(IERC20(_token) == token, "Unsupported token");
        token.safeTransferFrom(_from, address(this), _value);
    }

    /// @notice Sets the provided address as a beneficiary allowing it to
    ///         withdraw all tokens from escrow. This function can be called only
    ///         by escrow owner.
    function setBeneficiary(IBeneficiaryContract _beneficiary) external onlyOwner {
        beneficiary = _beneficiary;
        emit BeneficiaryUpdated(address(beneficiary));
    }

    /// @notice Withdraws the specified number of tokens from escrow to the
    ///         beneficiary. If the beneficiary is not set, or there are
    ///         insufficient tokens in escrow, the function fails.
    function withdraw(uint256 amount) external onlyOwner {
        require(address(beneficiary) != address(0), "Beneficiary not assigned");

        uint256 balance = token.balanceOf(address(this));
        require(amount <= balance, "Not enough tokens for withdrawal");

        token.safeTransfer(address(beneficiary), amount);
        emit TokensWithdrawn(address(beneficiary), amount);

        beneficiary.__escrowSentTokens(amount);
    }

    /// @notice Withdraws all funds from a non-phased Escrow passed as
    ///         a parameter. For this function to succeed, this PhasedEscrow
    ///         has to be set as a beneficiary of the non-phased Escrow.
    function withdrawFromEscrow(Escrow _escrow) public {
        _escrow.withdraw();
    }
}
/// @title PhasedEscrow
/// @notice A token holder contract allowing contract owner to set beneficiary of
///         tokens held by the contract and allowing the owner to withdraw the
///         tokens to that beneficiary in phases.
function withdraw(uint256 amount) external onlyOwner {
    require(address(beneficiary) != address(0), "Beneficiary not assigned");

    uint256 balance = token.balanceOf(address(this));
    require(amount <= balance, "Not enough tokens for withdrawal");

    token.safeTransfer(address(beneficiary), amount);
    emit TokensWithdrawn(address(beneficiary), amount);

    beneficiary.__escrowSentTokens(amount);
}

/// @notice Withdraws the specified number of tokens from escrow to the
///         beneficiary. If the beneficiary is not set, or there are
///         insufficient tokens in escrow, the function fails.