contract IOAEX is Token {
    // The address of BDR contract
    BDRContract public BDRInstance;
    // The total amount of locked tokens at the specified address
    mapping(address => uint256) public totalLockAmount;
    // The released amount of the specified address
    mapping(address => uint256) public releasedAmount;
    // 
    mapping(address => timeAndAmount[]) public allocations;
    // Stores the timestamp and the amount of tokens released each time
    struct timeAndAmount {
        uint256 releaseTime;
        uint256 releaseAmount;
    }
    
    // events
    event LockToken(address _beneficiary, uint256 totalLockAmount);
    event ReleaseToken(address indexed user, uint256 releaseAmount, uint256 releaseTime);
    event ExchangeBDR(address from, uint256 value);
    event SetBDRContract(address BDRInstanceess);

    /**
     * @dev Throws if called by any account other than the BDR contract
     */
    modifier onlyBDRContract() {
        require(msg.sender == address(BDRInstance));
        _;
    }

    /**
     * @dev Constructor, to initialize the basic information of token
     */
    constructor (string memory _name, string memory _symbol, uint8 _decimals, uint256 _INIT_TOTALSUPPLY) Token (_name, _symbol, _decimals, _INIT_TOTALSUPPLY) public {

    }

    /**
     * @dev Sets the address of BDR contract
     */
    function setBDRContract(address BDRAddress) public onlyOwner {
        require(BDRAddress != address(0));
        BDRInstance = BDRContract(BDRAddress);
        emit SetBDRContract(BDRAddress);
    }
    
    /**
     * @dev The owner can call this function to send tokens to the specified address, but these tokens are only available for more than the specified time
     * @param _beneficiary The address to receive tokens
     * @param _releaseTimes Array, the timestamp for releasing token
     * @param _releaseAmount Array, the amount for releasing token 
     */
    function lockToken(address _beneficiary, uint256[] memory _releaseTimes, uint256[] memory _releaseAmount) public onlyOwner returns(bool) {
        
        require(totalLockAmount[_beneficiary] == 0); // The beneficiary is not in any lock-plans at the current timestamp.
        require(_beneficiary != address(0)); // The beneficiary cannot be an empty address
        require(_releaseTimes.length == _releaseAmount.length); // These two lists are equal in length.
        releasedAmount[_beneficiary] = 0;
        for (uint256 i = 0; i < _releaseTimes.length; i++) {
            totalLockAmount[_beneficiary] = totalLockAmount[_beneficiary].add(_releaseAmount[i]);
            require(_releaseAmount[i] > 0); // The amount to release is greater than 0.
            require(_releaseTimes[i] >= now); // Each release time is not lower than the current timestamp.
            // Saves the lock-token information
            allocations[_beneficiary].push(timeAndAmount(_releaseTimes[i], _releaseAmount[i]));
        }
        balances[owner] = balances[owner].sub(totalLockAmount[_beneficiary]); // Removes this part of the locked token from the owner
        emit LockToken(_beneficiary, totalLockAmount[_beneficiary]);
        return true;
    }

    /**
     * Releases token
     */
    function releaseToken() public returns (bool) {
        release(msg.sender); 
    }

    /**
     * @dev The basic function of releasing token
     */
    function release(address addr) internal {
        require(totalLockAmount[addr] > 0); // The address has joined a lock-plan.

        uint256 amount = releasableAmount(addr); // Gets the amount of release and updates the lock-plans data
        // Unlocks token. Converting locked tokens into normal tokens
        balances[addr] = balances[addr].add(amount);
        // Updates the amount of released tokens.
        releasedAmount[addr] = releasedAmount[addr].add(amount);
        // If the token on this address has been completely released, clears the Record of locking token
        if (releasedAmount[addr] == totalLockAmount[addr]) {
            delete allocations[addr];
            totalLockAmount[addr] = 0;
        }
        emit ReleaseToken(addr, amount, now);
    }

    /**
     * @dev Gets the amount that can be released at current timestamps 
     * @param addr A specified address.
     */
    function releasableAmount(address addr) public view returns (uint256) {
        if(totalLockAmount[addr] == 0) {
            return 0;
        }
        uint256 num = 0;
        for (uint256 i = 0; i < allocations[addr].length; i++) {
            if (now >= allocations[addr][i].releaseTime) { // Determines the releasable stage under the current timestamp.
                num = num.add(allocations[addr][i].releaseAmount);
            }
        }
        return num.sub(releasedAmount[addr]); // the amount of current timestamps that can be released - the released amount.
    }
    
    /**
     * @dev Gets the amount of tokens that are still locked at current timestamp.
     * @param addr A specified address.
     */
    function balanceOfLocked(address addr) public view returns(uint256) {
        if (totalLockAmount[addr] > releasedAmount[addr]) {
            return totalLockAmount[addr].sub(releasedAmount[addr]);
        } else {
            return 0;
        }
        
    }

    /**
     * @dev Transfers token to a specified address. 
     *      If 'msg.sender' has releasable tokens, this part of the token will be released automatically.
     *      If the target address of transferring is BDR contract, the operation of changing BDR tokens will be executed.
     * @param to The target address of transfer, which may be the BDR contract
     * @param value The amount of tokens transferred
     */
    function transfer(address to, uint value) public returns (bool) {
        if(releasableAmount(msg.sender) > 0) {
            release(msg.sender); // Calls 'release' function
        }
        super.transfer(to, value); // Transfers tokens to address 'to'
        if(to == address(BDRInstance)) {
            BDRInstance.tokenFallback(msg.sender, value, bytes("")); // Calls 'tokenFallback' function in BDR contract to exchange tokens
            emit ExchangeBDR(msg.sender, value);
        }
        return true;
    }

    /**
     * @dev Transfers tokens from one address to another.
     *      If 'from' has releasable tokens, this part of the token will be released automatically.
     *      If the target address of transferring is  BDR contract, the operation of changing BDR tokens will be executed.
     * @param from The address which you want to send tokens from
     * @param to The address which you want to transfer to
     * @param value The amount of tokens to be transferred
     */
    function transferFrom(address from, address to, uint value) public returns (bool) {
        if(releasableAmount(from) > 0) {
            release(from); // Calls the 'release' function
        }
        super.transferFrom(from, to, value); // Transfers token to address 'to'
        if(to == address(BDRInstance)) {
            BDRInstance.tokenFallback(from, value, bytes("")); // Calls 'tokenFallback' function in BDR contract to exchange tokens
            emit ExchangeBDR(from, value);
        }
        return true;
    }

    /**
     * @dev Function that is called by the BDR contract to exchange 'Abc' tokens
     */
    function tokenFallback(address from, uint256 value, bytes calldata) external onlyBDRContract {
        require(from != address(0));
        require(value != uint256(0));
        
        uint256 AbcValue = value.mul(10**uint256(decimals)).div(10**uint256(BDRInstance.decimals())); // Calculates the number of 'Abc' tokens that can be exchanged
        require(AbcValue <= balances[address(BDRInstance)]);
        balances[address(BDRInstance)] = balances[address(BDRInstance)].sub(AbcValue);
        balances[from] = balances[from].add(AbcValue);
        emit Transfer(owner, from, AbcValue);
    }
    
}
/**
 * @title IOAEX ENTITY TOKEN
 */
function releaseToken() public returns (bool) {
        release(msg.sender); 
    }
/**
 * Releases token
 */