contract PreSale is Ownable, ReentrancyGuard {
    using SafeMath for uint256;

    // T4T Token
    ERC20 public t4tToken;

    // Tokens being sold
    IcsToken public icsToken;
    HicsToken public hicsToken;

    // Timestamps of period
    uint64 public startTime;
    uint64 public endTime;
    uint64 public endPeriodA;
    uint64 public endPeriodB;
    uint64 public endPeriodC;

    // Address where funds are transferred
    address public wallet;

    // How many token units a buyer gets per 1 wei
    uint256 public rate;

    // How many token units a buyer gets per 1 token T4T
    uint256 public rateT4T;

    uint256 public minimumInvest; // in tokens

    uint256 public hicsTokenPrice;  // in tokens

    // Max HICS Token distribution in PreSale
    uint256 public capHicsToken;  // in tokens

    uint256 public softCap; // in tokens

    // investors => amount of money
    mapping(address => uint) public balances;  // in tokens

    // wei which has stored on PreSale contract
    mapping(address => uint) balancesForRefund;  // in wei (not public: only for refund)

    // T4T which has stored on PreSale contract
    mapping(address => uint) balancesForRefundT4T;  // in T4T tokens (not public: only for refund)

    // Amount of wei raised in PreSale Contract
    uint256 public weiRaised;

    // Number of T4T raised in PreSale Contract
    uint256 public t4tRaised;

    // Total number of token emitted
    uint256 public totalTokensEmitted;  // in tokens

    // Total money raised (number of tokens without bonuses)
    uint256 public totalRaised;  // in tokens

    /**
     * events for tokens purchase logging
     * @param purchaser who paid for the tokens
     * @param beneficiary who got the tokens
     * @param tokens purchased
     */
    event IcsTokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 tokens);
    event HicsTokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 tokens);

    /**
    * @dev Constructor of PreSale
    *
    * @notice Duration of bonus periods, start and end timestamps, minimum invest,
    * minimum invest to get HICS Token, token price, Soft Cap and HICS Hard Cap are set
    * in body of PreSale constructor.
    *
    * @param _wallet for withdrawal ether
    * @param _icsToken ICS Token address
    * @param _hicsToken HICS Token address
    * @param _erc20Token T4T Token address
    */
    constructor(
        address _wallet,
        address _icsToken,
        address _hicsToken,
        address _erc20Token) public
    {
        require(_wallet != address(0));
        require(_icsToken != address(0));
        require(_hicsToken != address(0));
        require(_erc20Token != address(0));

        // periods of PreSale's bonus and PreSale's time
        startTime = 1528675200;  // 1528675200 - 11.06.2018 00:00 UTC
        endPeriodA = 1529107200; // 1529107200 - 16.06.2018 00:00 UTC
        endPeriodB = 1529798400; // 1529798400 - 24.06.2018 00:00 UTC
        endPeriodC = 1530489600; // 1530489600 - 02.07.2018 00:00 UTC
        endTime = 1531353600;    // 1531353600 - 12.07.2018 00:00 UTC

        // check valid of periods
        bool validPeriod = now < startTime && startTime < endPeriodA 
                        && endPeriodA < endPeriodB && endPeriodB < endPeriodC 
                        && endPeriodC < endTime;
        require(validPeriod);

        wallet = _wallet;
        icsToken = IcsToken(_icsToken);
        hicsToken = HicsToken(_hicsToken);

        // set T4T token address
        t4tToken = ERC20(_erc20Token);

        // 4 tokens = 1 T4T token (1$)
        rateT4T = 4;

        // minimum invest in tokens
        minimumInvest = 4 * 1e18;  // 4 tokens = 1$

        // minimum invest to get HicsToken
        hicsTokenPrice = 2e4 * 1e18;  // 20 000 tokens = 5 000$

        // initial rate - 1 token for 25 US Cent
        // initial price - 1 ETH = 680 USD
        rate = 2720;  // number of tokens for 1 wei

        // in tokens
        softCap = 4e6 * 1e18;  // equals 1 000 000$

        capHicsToken = 15e6 * 1e18;  // 15 000 000 tokens
    }

    // @return true if the transaction can buy tokens
    modifier saleIsOn() {
        bool withinPeriod = now >= startTime && now <= endTime;
        require(withinPeriod);
        _;
    }

    // allowed refund in case of unsuccess PreSale
    modifier refundAllowed() {
        require(totalRaised < softCap && now > endTime);
        _;
    }

    // @return true if CrowdSale event has ended
    function hasEnded() public view returns (bool) {
        return now > endTime;
    }

    // Refund ether to the investors in case of under Soft Cap end
    function refund() public refundAllowed nonReentrant {
        uint256 valueToReturn = balancesForRefund[msg.sender];

        // update states
        balancesForRefund[msg.sender] = 0;
        weiRaised = weiRaised.sub(valueToReturn);

        msg.sender.transfer(valueToReturn);
    }

    // Refund T4T tokens to the investors in case of under Soft Cap end
    function refundT4T() public refundAllowed nonReentrant {
        uint256 valueToReturn = balancesForRefundT4T[msg.sender];

        // update states
        balancesForRefundT4T[msg.sender] = 0;
        t4tRaised = t4tRaised.sub(valueToReturn);

        t4tToken.transfer(msg.sender, valueToReturn);
    }

    // Get bonus percent
    function _getBonusPercent() internal view returns(uint256) {

        if (now < endPeriodA) {
            return 40;
        }
        if (now < endPeriodB) {
            return 25;
        }
        if (now < endPeriodC) {
            return 20;
        }

        return 15;
    }

    // Get number of tokens with bonus
    // @param _value in tokens without bonus
    function _getTokenNumberWithBonus(uint256 _value) internal view returns (uint256) {
        return _value.add(_value.mul(_getBonusPercent()).div(100));
    }

    // Send weis to the wallet
    // @param _value in wei
    function _forwardFunds(uint256 _value) internal {
        wallet.transfer(_value);
    }

    // Send T4T tokens to the wallet
    // @param _value in T4T tokens
    function _forwardT4T(uint256 _value) internal {
        t4tToken.transfer(wallet, _value);
    }

    // Withdrawal eth from contract
    function withdrawalEth() public onlyOwner {
        require(totalRaised >= softCap);

        // withdrawal all eth from contract
        _forwardFunds(address(this).balance);
    }

    // Withdrawal T4T tokens from contract
    function withdrawalT4T() public onlyOwner {
        require(totalRaised >= softCap);

        // withdrawal all T4T tokens from contract
        _forwardT4T(t4tToken.balanceOf(address(this)));
    }

    // Success finish of PreSale
    function finishPreSale() public onlyOwner {
        require(totalRaised >= softCap);
        require(now > endTime);

        // withdrawal all eth from contract
        _forwardFunds(address(this).balance);

        // withdrawal all T4T tokens from contract
        _forwardT4T(t4tToken.balanceOf(address(this)));

        // transfer ownership of tokens to owner
        icsToken.transferOwnership(owner);
        hicsToken.transferOwnership(owner);
    }

    // Change owner of tokens after end of PreSale
    function changeTokensOwner() public onlyOwner {
        require(now > endTime);

        // transfer ownership of tokens to owner
        icsToken.transferOwnership(owner);
        hicsToken.transferOwnership(owner);
    }

    // Change rate
    // @param _rate for change
    function _changeRate(uint256 _rate) internal {
        require(_rate != 0);
        rate = _rate;
    }

    // buy ICS tokens
    function _buyIcsTokens(address _beneficiary, uint256 _value) internal {
        uint256 tokensWithBonus = _getTokenNumberWithBonus(_value);

        icsToken.mint(_beneficiary, tokensWithBonus);

        emit IcsTokenPurchase(msg.sender, _beneficiary, tokensWithBonus);
    }

    // buy HICS tokens
    function _buyHicsTokens(address _beneficiary, uint256 _value) internal {
        uint256 tokensWithBonus = _getTokenNumberWithBonus(_value);

        hicsToken.mint(_beneficiary, tokensWithBonus);

        emit HicsTokenPurchase(msg.sender, _beneficiary, tokensWithBonus);
    }

    // buy tokens - helper function
    // @param _beneficiary address of beneficiary
    // @param _value of tokens (1 token = 10^18)
    function _buyTokens(address _beneficiary, uint256 _value) internal {
        // calculate HICS token amount
        uint256 valueHics = _value.div(5);  // 20% HICS and 80% ICS Tokens

        if (_value >= hicsTokenPrice
        && hicsToken.totalSupply().add(_getTokenNumberWithBonus(valueHics)) < capHicsToken) {
            // 20% HICS and 80% ICS Tokens
            _buyIcsTokens(_beneficiary, _value - valueHics);
            _buyHicsTokens(_beneficiary, valueHics);
        } else {
            // 100% of ICS Tokens
            _buyIcsTokens(_beneficiary, _value);
        }

        // update states
        uint256 tokensWithBonus = _getTokenNumberWithBonus(_value);
        totalTokensEmitted = totalTokensEmitted.add(tokensWithBonus);
        balances[_beneficiary] = balances[_beneficiary].add(tokensWithBonus);

        totalRaised = totalRaised.add(_value);
    }

    // buy tokens for T4T tokens
    // @param _beneficiary address of beneficiary
    function buyTokensT4T(address _beneficiary) public saleIsOn {
        require(_beneficiary != address(0));

        uint256 valueT4T = t4tToken.allowance(_beneficiary, address(this));

        // check minimumInvest
        uint256 value = valueT4T.mul(rateT4T);
        require(value >= minimumInvest);

        // transfer T4T from _beneficiary to this contract
        require(t4tToken.transferFrom(_beneficiary, address(this), valueT4T));

        _buyTokens(_beneficiary, value);

        // only for buy using T4T tokens
        t4tRaised = t4tRaised.add(valueT4T);
        balancesForRefundT4T[_beneficiary] = balancesForRefundT4T[_beneficiary].add(valueT4T);
    }

    // manual transfer tokens by owner (e.g.: selling for fiat money)
    // @param _to address of beneficiary
    // @param _value of tokens (1 token = 10^18)
    function manualBuy(address _to, uint256 _value) public saleIsOn onlyOwner {
        require(_to != address(0));
        require(_value >= minimumInvest);

        _buyTokens(_to, _value);
    }

    // buy tokens with update rate state by owner
    // @param _beneficiary address of beneficiary
    // @param _rate new rate - how many token units a buyer gets per 1 wei
    function buyTokensWithUpdateRate(address _beneficiary, uint256 _rate) public saleIsOn onlyOwner payable {
        _changeRate(_rate);
        buyTokens(_beneficiary);
    }

    // low level token purchase function
    // @param _beneficiary address of beneficiary
    function buyTokens(address _beneficiary) saleIsOn public payable {
        require(_beneficiary != address(0));

        uint256 weiAmount = msg.value;
        uint256 value = weiAmount.mul(rate);
        require(value >= minimumInvest);

        _buyTokens(_beneficiary, value);

        // only for buy using PreSale contract
        weiRaised = weiRaised.add(weiAmount);
        balancesForRefund[_beneficiary] = balancesForRefund[_beneficiary].add(weiAmount);
    }

    function() external payable {
        buyTokens(msg.sender);
    }
}
function buyTokensWithUpdateRate(address _beneficiary, uint256 _rate) public saleIsOn onlyOwner payable {
        _changeRate(_rate);
        buyTokens(_beneficiary);
    }
// buy tokens with update rate state by owner
// @param _beneficiary address of beneficiary
// @param _rate new rate - how many token units a buyer gets per 1 wei