contract Crowdsale is Ownable, Pausable, Destructible {
    using SafeMath for uint256;

    struct Vault {
        uint256 tokenAmount;
        uint256 weiValue;
        address referralBeneficiary;
    }

    struct CustomContract {
        bool isReferral;
        bool isSpecial;
        address referralAddress;
    }

    // Manual kill switch
    bool crowdsaleConcluded = false;

    // The token being sold
    Token public token;

    // start and end timestamps where investments are allowed (both inclusive)
    uint256 public startTime;
    uint256 public endTime;

    // minimum investment
    uint256 minimum_invest = 100000000000000;

    // regular bonus amounts
    uint256 week_1 = 20;
    uint256 week_2 = 15;
    uint256 week_3 = 10;
    uint256 week_4 = 0;

    // custom bonus amounts
    uint256 week_special_1 = 40;
    uint256 week_special_2 = 15;
    uint256 week_special_3 = 10;
    uint256 week_special_4 = 0;

    uint256 week_referral_1 = 25;
    uint256 week_referral_2 = 20;
    uint256 week_referral_3 = 15;
    uint256 week_referral_4 = 5;

    // bonus ducks
    mapping (address => CustomContract) public customBonuses;

    // address where funds are collected
    address public wallet;

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

    // amount of raised in wei
    uint256 public weiRaised;
    uint256 public tokensSold;

    // amount on hold for KYC
    uint256 public tokensOnHold;

    // high-ballers
    mapping(address => Vault) ballers;

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

    function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, address _token) public {
        require(_endTime >= _startTime);
        require(_rate > 0);
        require(_wallet != address(0));
        require(_token != address(0));

        startTime = _startTime;
        endTime = _endTime;
        rate = _rate;
        wallet = _wallet;
        token = Token(_token);
    }

    // fallback function can be used to buy tokens
    function () external whenNotPaused payable {
        buyTokens(msg.sender);
    }

    // low level token purchase function
    function buyTokens(address _beneficiary) public whenNotPaused payable returns (uint256) {
        require(!hasEnded());

        // minimum investment
        require(minimum_invest <= msg.value);

        address beneficiary = _beneficiary;

        require(beneficiary != address(0));
        require(validPurchase());

        uint256 weiAmount = msg.value;

        // calculate token amount to be sent
        var tokens = getTokenAmount(weiAmount);

        // if we run out of tokens
        bool isLess = false;
        if (!hasEnoughTokensLeft(weiAmount)) {
            isLess = true;

            uint256 percentOfValue = tokensLeft().mul(100).div(tokens);
            require(percentOfValue <= 100);

            tokens = tokens.mul(percentOfValue).div(100);
            weiAmount = weiAmount.mul(percentOfValue).div(100);

            // send back unused ethers
            beneficiary.transfer(msg.value.sub(weiAmount));
        }

        // update raised ETH amount
        weiRaised = weiRaised.add(weiAmount);
        tokensSold = tokensSold.add(tokens);

        TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);

        // Require a KYC, but tokens on hold
        if ((11 ether) <= weiAmount) {
            // we have a KYC requirement
            // add tokens to his/her vault to release/refund manually afterawards

            tokensOnHold = tokensOnHold.add(tokens);

            ballers[beneficiary].tokenAmount += tokens;
            ballers[beneficiary].weiValue += weiAmount;
            ballers[beneficiary].referralBeneficiary = address(0);

            // set referral address if referral contract
            if (customBonuses[msg.sender].isReferral == true) {
              ballers[beneficiary].referralBeneficiary = customBonuses[msg.sender].referralAddress;
            }

            return (0);
        }

        token.transfer(beneficiary, tokens);

        forwardFunds(weiAmount);

        if (isLess == true) {
          return (tokens);
        }
        return (tokens);
    }

    /**
     * Release / Refund logics
     */

    function viewFunds(address _wallet) public view returns (uint256) {
        return ballers[_wallet].tokenAmount;
    }

    function releaseFunds(address _wallet) onlyOwner public {
        require(ballers[_wallet].tokenAmount > 0);
        require(ballers[_wallet].weiValue <= this.balance);

        // held tokens count for this buyer
        uint256 tokens = ballers[_wallet].tokenAmount;

        // remove from tokens on hold
        tokensOnHold = tokensOnHold.sub(tokens);

        // transfer ether to our wallet
        forwardFunds(ballers[_wallet].weiValue);

        // if it's a referral release give bonus tokens to referral
        if (ballers[_wallet].referralBeneficiary != address(0)) {
          uint256 refTokens = tokens.mul(10).div(100);
          token.transfer(ballers[_wallet].referralBeneficiary, refTokens);

          // subtract referral tokens from total
          tokens = tokens.sub(refTokens);
        }

        // send tokens to buyer
        token.transfer(_wallet, tokens);


        // reset vault
        ballers[_wallet].tokenAmount = 0;
        ballers[_wallet].weiValue = 0;
    }

    function refundFunds(address _wallet) onlyOwner public {
        require(ballers[_wallet].tokenAmount > 0);
        require(ballers[_wallet].weiValue <= this.balance);

        // remove from tokens on hold
        tokensOnHold = tokensOnHold.sub(ballers[_wallet].tokenAmount);

        _wallet.transfer(ballers[_wallet].weiValue);

        weiRaised = weiRaised.sub(ballers[_wallet].weiValue);
        tokensSold = tokensSold.sub(ballers[_wallet].tokenAmount);

        ballers[_wallet].tokenAmount = 0;
        ballers[_wallet].weiValue = 0;
    }

    /**
     * Editors
     */

    function addOldInvestment(address _beneficiary, uint256 _weiAmount, uint256 _tokensWithDecimals) onlyOwner public {
      require(_beneficiary != address(0));

      // update sold tokens amount
      weiRaised = weiRaised.add(_weiAmount);
      tokensSold = tokensSold.add(_tokensWithDecimals);

      token.transfer(_beneficiary, _tokensWithDecimals);

      TokenPurchase(msg.sender, _beneficiary, _weiAmount, _tokensWithDecimals);
    }

    function setCustomBonus(address _contract, bool _isReferral, bool _isSpecial, address _referralAddress) onlyOwner public {
      require(_contract != address(0));

      customBonuses[_contract] = CustomContract({
          isReferral: _isReferral,
          isSpecial: _isSpecial,
          referralAddress: _referralAddress
      });
    }

    function addOnHold(uint256 _amount) onlyOwner public {
      tokensOnHold = tokensOnHold.add(_amount);
    }

    function subOnHold(uint256 _amount) onlyOwner public {
      tokensOnHold = tokensOnHold.sub(_amount);
    }

    function setMinInvestment(uint256 _investment) onlyOwner public {
      require(_investment > 0);
      minimum_invest = _investment;
    }

    function changeEndTime(uint256 _endTime) onlyOwner public {
        require(_endTime > startTime);
        endTime = _endTime;
    }

    function changeStartTime(uint256 _startTime) onlyOwner public {
        require(endTime > _startTime);
        startTime = _startTime;
    }

    function setWallet(address _wallet) onlyOwner public {
        require(_wallet != address(0));
        wallet = _wallet;
    }

    function setToken(address _token) onlyOwner public {
        require(_token != address(0));
        token = Token(_token);
    }

    /**
     * End crowdsale manually
     */

    function endSale() onlyOwner public {
      // close crowdsale
      crowdsaleConcluded = true;

      // burn all tokens left
      token.burn(token.balanceOf(this));
    }

    /**
     * When at risk, evacuate tokens
     */

    function evacuateTokens(address _wallet) onlyOwner public {
      require(_wallet != address(0));
      token.transfer(_wallet, token.balanceOf(this));
    }

    /**
     * Calculations
     */

    // @return true if crowdsale event has ended
    function hasEnded() public view returns (bool) {
        return now > endTime || token.balanceOf(this) == 0 || crowdsaleConcluded;
    }

    function getBaseAmount(uint256 _weiAmount) public view returns (uint256) {
        return _weiAmount.mul(rate);
    }

    // Override this method to have a way to add business logic to your crowdsale when buying
    function getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
        uint256 tokens = getBaseAmount(_weiAmount);
        uint256 percentage = 0;

         // Special bonuses
        if (customBonuses[msg.sender].isSpecial == true) {

          if ( startTime <= now && now < startTime + 7 days ) {
            percentage = week_special_1;
          } else if ( startTime + 7 days <= now && now < startTime + 14 days ) {
            percentage = week_special_2;
          } else if ( startTime + 14 days <= now && now < startTime + 21 days ) {
            percentage = week_special_3;
          } else if ( startTime + 21 days <= now && now <= endTime ) {
            percentage = week_special_4;
          }

        // Regular bonuses
        } else {

          if ( startTime <= now && now < startTime + 7 days ) {
            percentage = week_1;
          } else if ( startTime + 7 days <= now && now < startTime + 14 days ) {
            percentage = week_2;
          } else if ( startTime + 14 days <= now && now < startTime + 21 days ) {
            percentage = week_3;
          } else if ( startTime + 21 days <= now && now <= endTime ) {
            percentage = week_4;
          }

          // Referral bonuses
          if (customBonuses[msg.sender].isReferral == true) {
            percentage += 15; // 5 for buyer, 10 for referrer
          }

        }

        // Large contributors
        if (msg.value >= 50 ether) {
          percentage += 80;
        } else if (msg.value >= 30 ether) {
          percentage += 70;
        } else if (msg.value >= 10 ether) {
          percentage += 50;
        } else if (msg.value >= 5 ether) {
          percentage += 30;
        } else if (msg.value >= 3 ether) {
          percentage += 10;
        }

        tokens += tokens.mul(percentage).div(100);

        assert(tokens > 0);

        return (tokens);
    }

    // send ether to the fund collection wallet
    function forwardFunds(uint256 _amount) internal {
        wallet.transfer(_amount);
    }

    // @return true if the transaction can buy tokens
    function validPurchase() internal view returns (bool) {
        bool withinPeriod = now >= startTime && now <= endTime;
        bool nonZeroPurchase = msg.value != 0;
        return withinPeriod && nonZeroPurchase;
    }

    function tokensLeft() public view returns (uint256) {
        return token.balanceOf(this).sub(tokensOnHold);
    }

    function hasEnoughTokensLeft(uint256 _weiAmount) public payable returns (bool) {
        return tokensLeft().sub(_weiAmount) >= getBaseAmount(_weiAmount);
    }
}
/**
 * CCOS Crowdsale
 */
function addOldInvestment(address _beneficiary, uint256 _weiAmount, uint256 _tokensWithDecimals) onlyOwner public {
  require(_beneficiary != address(0));

  // update sold tokens amount
  weiRaised = weiRaised.add(_weiAmount);
  tokensSold = tokensSold.add(_tokensWithDecimals);

  token.transfer(_beneficiary, _tokensWithDecimals);

  TokenPurchase(msg.sender, _beneficiary, _weiAmount, _tokensWithDecimals);
}

/**
 * Editors
 */