contract IiinoCoinCrowdsale is Crowdsale, Pausable, ReentrancyGuard {
    event ReferralAwarded(address indexed purchaser, address indexed referrer, uint256 iiinoPurchased, uint256 iiinoAwarded);

    using SafeMath for uint256;
    
    address devWallet;
    uint256 noOfTokenAlocatedForDev;
    uint256 public noOfTokenAlocatedForSeedRound;
    uint256 public noOfTokenAlocatedForPresaleRound;
    uint256 public totalNoOfTokenAlocated;
    uint256 public noOfTokenAlocatedPerICOPhase; //The token allocation for each phase of the ICO
    uint256 public noOfICOPhases; //No. of ICO phases
    uint256 public seedRoundEndTime; // to be in seconds
    uint256 public thresholdEtherLimitForSeedRound; //minimum amount of wei needed to participate
    uint256 public moreTokenPerEtherForSeedRound; // the more amount of Iiinos given per ether during seed round
    uint256 public moreTokenPerEtherForPresaleRound; //the more amount of Iiinos given per ether during presale round
    
    uint256 public referralTokensAvailable; //To hold the value of the referral token limit.
    uint256 public referralPercent; //The percentage of referral to be awarded on each order with a referrer
    uint256 public referralTokensAllocated; // To hold the total number of token allocated to referrals

    uint256 public presaleEndTime; // to be in seconds
    uint256 public issueRateDecDuringICO; //The number of iiino that needs to be decreased for every next phase of the ICO 
    //uint256 public percentToMintPerDuration; //The percentage of Genesis ICO that will be minted every minting cycle
    //uint256 public durationBetweenRewardMints; //The length of a reward minting cycle
    

    function IiinoCoinCrowdsale(
        uint256[] _params, // All the params that need to initialize the crowdsale as well as the iiino Token
        address _wallet, 
        address _devTeamWallet,
        address _iiinoTokenAddress
    ) public Crowdsale(_params[0], _params[1], _params[4], _wallet) {
        devWallet = _devTeamWallet;
        issueRateDecDuringICO = _params[5];
        seedRoundEndTime = _params[2];
        presaleEndTime = _params[3];
          
        moreTokenPerEtherForSeedRound = _params[13];
        moreTokenPerEtherForPresaleRound = _params[14];
          
        referralTokensAvailable = _params[15];
        referralTokensAllocated = _params[15]; //Initially all the allocated tokens are available
        referralPercent = _params[16];

        noOfTokenAlocatedForDev = _params[6];
        noOfTokenAlocatedForSeedRound = _params[7];
        noOfTokenAlocatedForPresaleRound = _params[8];
        totalNoOfTokenAlocated = _params[10];
        noOfTokenAlocatedPerICOPhase = _params[9];
        noOfICOPhases = _params[11];
        thresholdEtherLimitForSeedRound = _params[12];

        //Neeed to test the total allocation with the sum of all allocations.
        //token.transferOwnership(msg.sender);

        //token.mint(_devTeamWallet, noOfTokenAlocatedForDev);
        //iiinoTokenAddress = _iiinoTokenAddress;
        token = IiinoCoin(_iiinoTokenAddress);
    }

    function initialTransferToDevTeam() nonReentrant onlyOwner whenNotPaused external {
        require(devWallet != address(0));
        //To assign the initial dev tokens to the dev wallet
        token.mint(devWallet, noOfTokenAlocatedForDev);
        //Sets the devTeamWallet to 0x00, to restrict future transfers
        devWallet = address(0);
    }

    /*
    //Temp Function to retreive values
    function tempGetDataToCheck (uint indx, uint256 weiAmt) public view returns (uint256) {
      //string temp = "thresholdEtherLimitForSeedRound =>" + thresholdEtherLimitForSeedRound + "Total Supply => " + token.totalSupply() + "noOfTokenAlocatedForSeedRound => " + noOfTokenAlocatedForSeedRound + "noOfTokenAlocatedForDev => " + noOfTokenAlocatedForDev + "rate => " + rate;
        if (indx == 0)
          return issueRateDecDuringICO;
        else if (indx == 1)
          return seedRoundEndTime;
        else if (indx == 2)
          return presaleEndTime;
        else if (indx == 3)
          return moreTokenPerEtherForSeedRound;
        else if (indx == 4)
          return moreTokenPerEtherForPresaleRound;
        else if (indx == 5)
          return noOfTokenAlocatedForDev;
        else if (indx == 6)
          return noOfTokenAlocatedForSeedRound;
        else if (indx == 61)
          return noOfTokenAlocatedForPresaleRound;
        else if (indx == 7)
          return totalNoOfTokenAlocated;
        else if (indx == 8)
          return noOfTokenAlocatedPerICOPhase;
        else if (indx == 9)
          return noOfICOPhases;
        else if (indx == 10)
          return thresholdEtherLimitForSeedRound;
        else if (indx == 11)
          return 0;//percentToMintPerDuration;
        else if (indx == 12)
        {
            uint currentRate;
            uint256 icoMultiplier;
            (currentRate, icoMultiplier) = getCurrentRateInternal();
            return currentRate;//durationBetweenRewardMints;
        }  
        else if (indx == 13)
          return token.totalSupply();
        else if (indx == 14)
          return getTokenAmount(weiAmt);
        else if (indx == 15)
          return now;
        else if (indx == 16)
          return startTime;
        else if (indx == 17)
          return endTime;
        
    }
    */
    function getTokenAmount (uint256 weiAmount) whenNotPaused internal view returns (uint256) {
        uint currRate;
        uint256 multiplierForICO;
        uint256 amountOfIiino = 0;
        uint256 referralsDistributed = referralTokensAllocated.sub(referralTokensAvailable);
        uint256 _totalSupply = (token.totalSupply()).sub(referralsDistributed);
        if (now <= seedRoundEndTime) {
          
            require(weiAmount >= thresholdEtherLimitForSeedRound);
            require(_totalSupply < noOfTokenAlocatedForSeedRound.add(noOfTokenAlocatedForDev));
            (currRate, multiplierForICO) = getCurrentRateInternal();
            
            amountOfIiino = weiAmount.mul(currRate);
            
            //Only if there is enough available amount of iiino in the phase will it allocate it, else it will just revert the transaction and return the ether 
            require (_totalSupply.add(amountOfIiino) <= noOfTokenAlocatedForSeedRound.add(noOfTokenAlocatedForDev));
            return amountOfIiino;

        } else if (now <= presaleEndTime) {
            require(_totalSupply < noOfTokenAlocatedForSeedRound.add(noOfTokenAlocatedForPresaleRound).add(noOfTokenAlocatedForDev));
            (currRate, multiplierForICO) = getCurrentRateInternal();
            
            amountOfIiino = weiAmount.mul(currRate);
            //Only if there is enough available amount of iiino in the phase will it allocate it, else it will just revert the transaction and return the ether 
            require (_totalSupply.add(amountOfIiino) <= noOfTokenAlocatedForSeedRound.add(noOfTokenAlocatedForPresaleRound).add(noOfTokenAlocatedForDev));
            return amountOfIiino;
        } else {
            
           
            require(_totalSupply < noOfTokenAlocatedForSeedRound.add(noOfTokenAlocatedForPresaleRound).add(noOfTokenAlocatedForDev));
            require(now < endTime);
            
            (currRate,multiplierForICO) = getCurrentRateInternal();
            //To check if the amount of tokens for the current ICO phase is exhausted
            //uint256 a = 1;
            //amountOfIiino = (weiAmount.mul(currRate)).div(a);
            
            amountOfIiino = weiAmount * currRate;
            
            require(_totalSupply.add(amountOfIiino) <= noOfTokenAlocatedForSeedRound.add(noOfTokenAlocatedForPresaleRound).add(noOfTokenAlocatedForDev).add(noOfTokenAlocatedPerICOPhase.mul(multiplierForICO.add(1))));
            return amountOfIiino;
          
        }
      
    }

  //function getCurrentRate returns the amount of iii for the amount of wei at the current point in time (now)
    function getCurrentRateInternal() whenNotPaused internal view returns (uint,uint256) {
        uint currRate;
        uint256 multiplierForICO = 0; 

        if (now <= seedRoundEndTime) {
            currRate = rate.add(moreTokenPerEtherForSeedRound);
        } else if (now <= presaleEndTime) {
            currRate = rate.add(moreTokenPerEtherForPresaleRound);
        } else {
            multiplierForICO = (now.sub(presaleEndTime)).div(30 days); //86400 seconds in a day
            currRate = rate.sub((issueRateDecDuringICO.mul(multiplierForICO)));
            require(multiplierForICO < noOfICOPhases);
        }
        return (currRate,multiplierForICO);
    }
    
    function buyTokensWithReferrer(address referrer) nonReentrant whenNotPaused external payable {
        address beneficiary = msg.sender;
        require(referrer != address(0));
        require(beneficiary != address(0));
        require(validPurchase());
        require(msg.value >= (0.01 ether));

        uint256 weiAmount = msg.value;

        // calculate token amount to be created
        uint256 tokens = getTokenAmount(weiAmount);

        // update state
        weiRaised = weiRaised.add(weiAmount);

        token.mint(beneficiary, tokens);
        emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);

        //To send the referrer his percentage of tokens.
        uint256 referrerTokens = tokens.mul(referralPercent).div(100);
        if (referralTokensAvailable > 0) {
            if (referrerTokens > referralTokensAvailable) {
                referrerTokens = referralTokensAvailable;
            }
            
            token.mint(referrer, referrerTokens);
            referralTokensAvailable = referralTokensAvailable.sub(referrerTokens);
            emit ReferralAwarded(msg.sender, referrer, tokens, referrerTokens);

        }
        
        forwardFunds();

    }

    function getCurrentRate() whenNotPaused external view returns (uint,uint256) {
        return getCurrentRateInternal ();
    }

    function buyTokens(address beneficiary) nonReentrant whenNotPaused external payable {
        buyTokensInternal(beneficiary);
    }

    function forwardFunds() whenNotPaused internal {
        super.forwardFunds();
    }

}
function getTokenAmount (uint256 weiAmount) whenNotPaused internal view returns (uint256) {
        uint currRate;
        uint256 multiplierForICO;
        uint256 amountOfIiino = 0;
        uint256 referralsDistributed = referralTokensAllocated.sub(referralTokensAvailable);
        uint256 _totalSupply = (token.totalSupply()).sub(referralsDistributed);
        if (now <= seedRoundEndTime) {
          
            require(weiAmount >= thresholdEtherLimitForSeedRound);
            require(_totalSupply < noOfTokenAlocatedForSeedRound.add(noOfTokenAlocatedForDev));
            (currRate, multiplierForICO) = getCurrentRateInternal();
            
            amountOfIiino = weiAmount.mul(currRate);
            
            //Only if there is enough available amount of iiino in the phase will it allocate it, else it will just revert the transaction and return the ether 
            require (_totalSupply.add(amountOfIiino) <= noOfTokenAlocatedForSeedRound.add(noOfTokenAlocatedForDev));
            return amountOfIiino;

        } else if (now <= presaleEndTime) {
            require(_totalSupply < noOfTokenAlocatedForSeedRound.add(noOfTokenAlocatedForPresaleRound).add(noOfTokenAlocatedForDev));
            (currRate, multiplierForICO) = getCurrentRateInternal();
            
            amountOfIiino = weiAmount.mul(currRate);
            //Only if there is enough available amount of iiino in the phase will it allocate it, else it will just revert the transaction and return the ether 
            require (_totalSupply.add(amountOfIiino) <= noOfTokenAlocatedForSeedRound.add(noOfTokenAlocatedForPresaleRound).add(noOfTokenAlocatedForDev));
            return amountOfIiino;
        } else {
            
           
            require(_totalSupply < noOfTokenAlocatedForSeedRound.add(noOfTokenAlocatedForPresaleRound).add(noOfTokenAlocatedForDev));
            require(now < endTime);
            
            (currRate,multiplierForICO) = getCurrentRateInternal();
            //To check if the amount of tokens for the current ICO phase is exhausted
            //uint256 a = 1;
            //amountOfIiino = (weiAmount.mul(currRate)).div(a);
            
            amountOfIiino = weiAmount * currRate;
            
            require(_totalSupply.add(amountOfIiino) <= noOfTokenAlocatedForSeedRound.add(noOfTokenAlocatedForPresaleRound).add(noOfTokenAlocatedForDev).add(noOfTokenAlocatedPerICOPhase.mul(multiplierForICO.add(1))));
            return amountOfIiino;
          
        }
      
    }
/*
 //Temp Function to retreive values
 function tempGetDataToCheck (uint indx, uint256 weiAmt) public view returns (uint256) {
 //string temp = "thresholdEtherLimitForSeedRound =>" + thresholdEtherLimitForSeedRound + "Total Supply => " + token.totalSupply() + "noOfTokenAlocatedForSeedRound => " + noOfTokenAlocatedForSeedRound + "noOfTokenAlocatedForDev => " + noOfTokenAlocatedForDev + "rate => " + rate;
 if (indx == 0)
 return issueRateDecDuringICO;
 else if (indx == 1)
 return seedRoundEndTime;
 else if (indx == 2)
 return presaleEndTime;
 else if (indx == 3)
 return moreTokenPerEtherForSeedRound;
 else if (indx == 4)
 return moreTokenPerEtherForPresaleRound;
 else if (indx == 5)
 return noOfTokenAlocatedForDev;
 else if (indx == 6)
 return noOfTokenAlocatedForSeedRound;
 else if (indx == 61)
 return noOfTokenAlocatedForPresaleRound;
 else if (indx == 7)
 return totalNoOfTokenAlocated;
 else if (indx == 8)
 return noOfTokenAlocatedPerICOPhase;
 else if (indx == 9)
 return noOfICOPhases;
 else if (indx == 10)
 return thresholdEtherLimitForSeedRound;
 else if (indx == 11)
 return 0;//percentToMintPerDuration;
 else if (indx == 12)
 {
 uint currentRate;
 uint256 icoMultiplier;
 (currentRate, icoMultiplier) = getCurrentRateInternal();
 return currentRate;//durationBetweenRewardMints;
 }  
 else if (indx == 13)
 return token.totalSupply();
 else if (indx == 14)
 return getTokenAmount(weiAmt);
 else if (indx == 15)
 return now;
 else if (indx == 16)
 return startTime;
 else if (indx == 17)
 return endTime;
 
 }
 */