contract IPCCrowdsale is Ownable {

    using SafeMath for uint;
    using SafeERC20 for IPCToken;


    IPCToken private _token = new IPCToken();

    uint currentPhase = 0;

    uint256  _weiRaised;

    uint8[] phase_bonuses =  [50, 0];

    uint256[] phase_supply_limits = [ 150000 ether, 400000 ether];

    address private _wallet = 0x67E6Efc62635353aE31d16AD844Cc4BDBCaCe53D;

    uint private usd_per_barrel_rate = 55;
    uint private eth_per_usd_rate = 21800 ;


    event TokensPurchased(
        address indexed purchaser,
        address indexed beneficiary,
        uint256 value,
        uint256 amount
    );


    constructor() public {
        transferOwnership(_wallet);
        _token._mint(_wallet, 50000 ether);
    
    }


    function startMainSale() public onlyOwner {
        require(currentPhase == 0);
        currentPhase = 1;
    }


    function() external payable {
        buyTokens(msg.sender);
    }


    function token() public view returns (IERC20) {
        return _token;
    }


    function wallet() public view returns (address) {
        return _wallet;
    }


    function rate() public view returns (uint256) {
        return eth_per_usd_rate.div(usd_per_barrel_rate);
    }

    function setBarrelPrice(uint _price){
        usd_per_barrel_rate =_price;
    }


    function setEtherPrice(uint _price){
        eth_per_usd_rate = _price;
    }


    /**
     * @return the mount of wei raised.
     */
    function weiRaised() public view returns (uint256) {
        return _weiRaised;
    }


    function get_max_supply() public view returns (uint256) {
        return phase_supply_limits[currentPhase];
    }


    function buyTokens(address beneficiary) public payable {

        uint256 weiAmount = msg.value;

        uint256 tokens = _getTokenAmount(weiAmount);
        uint256 bonus = tokens.mul(phase_bonuses[currentPhase]).div(100);
        _weiRaised = _weiRaised.add(weiAmount);
        

        _processPurchase(beneficiary, tokens + bonus);

        require(token().totalSupply() < get_max_supply());

        // emit TokensPurchased(
        //     msg.sender,
        //     beneficiary,
        //     weiAmount,
        //     tokens
        // );


        _forwardFunds();
    }




    function _deliverTokens(
        address beneficiary,
        uint256 tokenAmount
    )
    internal
    {
        _token._mint(beneficiary, tokenAmount);
    }


    function _processPurchase(
        address beneficiary,
        uint256 tokenAmount
    )
    internal
    {
        _deliverTokens(beneficiary, tokenAmount);
    }

    function _getTokenAmount(uint256 weiAmount)
    internal view returns (uint256)
    {
        return weiAmount.mul(rate()).div(100);
    }

    function _forwardFunds() internal {
        _wallet.transfer(msg.value);
    }
}
function weiRaised() public view returns (uint256) {
    return _weiRaised;
}

/**
 * @return the mount of wei raised.
 */