contract TokenSale is Ownable {
    //Event for when a token has been bought
    event TokensBought(uint256 amount);
    //Event for when ether is taken out of this contract
    event Withdrawal(uint256 amount);
    
    IERC20 public token;
    uint256 public price;
    
    constructor(address _token) public {
        token = IERC20(_token);
    }
    
    /**
    Set the price of tokens for the token sale
    */
    function setPrice(uint256 _price) public onlyOwner {
        price = _price;
    }
    
    /**
    Withdraw the amount from the contract's balance. Only the contract owner can execute this function
    */
    function withdraw(uint256 amount) public onlyOwner {
        uint256 balance = address(this).balance;

        require(amount <= balance, "Requested to much");
        
        address payable _owner = address(uint160(owner()));
        
        _owner.transfer(amount);

        emit Withdrawal(amount);
    }
    
    /**
    Get the amount of tokens this contract currently owns
    */
    function tokenBalance() public view returns (uint256) {
        return token.balanceOf(address(this));
    }
    
    /**
    Buy tokens from this contract
    */
    function buy(uint256 tokens) public payable returns (uint256) {
        require(tokens <= tokenBalance());
        
        uint256 total = tokens * price;
        
        require(msg.value >= total);
        
        uint256 change = msg.value - total;
        
        token.transfer(msg.sender, tokens);
        
        if (change > 0) {
            msg.sender.transfer(change);
        }
        
        emit TokensBought(tokens);
    }
}
function buy(uint256 tokens) public payable returns (uint256) {
    require(tokens <= tokenBalance());
        
    uint256 total = tokens * price;
        
    require(msg.value >= total);
        
    uint256 change = msg.value - total;
        
    token.transfer(msg.sender, tokens);
        
    if (change > 0) {
        msg.sender.transfer(change);
    }
        
    emit TokensBought(tokens);
}

/**
 Buy tokens from this contract
 */