contract BBBToken is StandardToken, Ownable {
    using SafeMath for uint256;

    // Token 資訊
    string  public constant NAME = "M724 Coin";
    string  public constant SYMBOL = "M724";
    uint8   public constant DECIMALS = 18;

    // Sale period1.
    uint256 public startDate1;
    uint256 public endDate1;

    // Sale period2.
    uint256 public startDate2;
    uint256 public endDate2;

     //目前銷售額
    uint256 public saleCap;

    // Address Where Token are keep
    address public tokenWallet;

    // Address where funds are collected.
    address public fundWallet;

    // Amount of raised money in wei.
    uint256 public weiRaised;

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

    // Modifiers
    modifier uninitialized() {
        require(tokenWallet == 0x0);
        require(fundWallet == 0x0);
        _;
    }

    constructor() public {}
    // Trigger with Transfer event
    // Fallback function can be used to buy tokens
    function () public payable {
        buyTokens(msg.sender, msg.value);
    }

    function getDate() public view returns(uint256 _date) {
        _date = getCurrentTimestamp();
    }

    //初始化合約
    function initialize(address _tokenWallet, address _fundWallet, uint256 _start1, uint256 _end1,
                        uint256 _saleCap, uint256 _totalSupply) public
                        onlyOwner uninitialized {
        //require(_start >= getCurrentTimestamp());
        require(_start1 < _end1);
        require(_tokenWallet != 0x0);
        require(_fundWallet != 0x0);
        require(_totalSupply >= _saleCap);

        startDate1 = _start1;
        endDate1 = _end1;
        saleCap = _saleCap;
        tokenWallet = _tokenWallet;
        fundWallet = _fundWallet;
        totalSupply = _totalSupply;

        balances[tokenWallet] = saleCap;
        balances[0xb1] = _totalSupply.sub(saleCap);
    }

    //設定銷售期間
    function setPeriod(uint period, uint256 _start, uint256 _end) public onlyOwner {
        require(_end > _start);
        if (period == 1) {
            startDate1 = _start;
            endDate1 = _end;
        }else if (period == 2) {
            require(_start > endDate1);
            startDate2 = _start;
            endDate2 = _end;      
        }
    }

    // For pushing pre-ICO records
    function sendForPreICO(address buyer, uint256 amount) public onlyOwner {
        require(saleCap >= amount);

        saleCap = saleCap - amount;
        // Transfer
        balances[tokenWallet] = balances[tokenWallet].sub(amount);
        balances[buyer] = balances[buyer].add(amount);
    }

        //Set SaleCap
    function setSaleCap(uint256 _saleCap) public onlyOwner {
        require(balances[0xb1].add(balances[tokenWallet]).sub(_saleCap) > 0);
        uint256 amount=0;
        //目前銷售額 大於 新銷售額
        if (balances[tokenWallet] > _saleCap) {
            amount = balances[tokenWallet].sub(_saleCap);
            balances[0xb1] = balances[0xb1].add(amount);
        } else {
            amount = _saleCap.sub(balances[tokenWallet]);
            balances[0xb1] = balances[0xb1].sub(amount);
        }
        balances[tokenWallet] = _saleCap;
        saleCap = _saleCap;
    }

    //Calcute Bouns
    function getBonusByTime(uint256 atTime) public constant returns (uint256) {
        if (atTime < startDate1) {
            return 0;
        } else if (endDate1 > atTime && atTime > startDate1) {
            return 5000;
        } else if (endDate2 > atTime && atTime > startDate2) {
            return 2500;
        } else {
            return 0;
        }
    }

    function getBounsByAmount(uint256 etherAmount, uint256 tokenAmount) public pure returns (uint256) {
        //最高40%
        uint256 bonusRatio = etherAmount.div(500 ether);
        if (bonusRatio > 4) {
            bonusRatio = 4;
        }
        uint256 bonusCount = SafeMath.mul(bonusRatio, 10);
        uint256 bouns = SafeMath.mul(tokenAmount, bonusCount);
        uint256 realBouns = SafeMath.div(bouns, 100);
        return realBouns;
    }

    //終止合約
    function finalize() public onlyOwner {
        require(!saleActive());

        // Transfer the rest of token to tokenWallet
        balances[tokenWallet] = balances[tokenWallet].add(balances[0xb1]);
        balances[0xb1] = 0;
    }
    
    //確認是否正常銷售
    function saleActive() public constant returns (bool) {
        return (
            (getCurrentTimestamp() >= startDate1 &&
                getCurrentTimestamp() < endDate1 && saleCap > 0) ||
            (getCurrentTimestamp() >= startDate2 &&
                getCurrentTimestamp() < endDate2 && saleCap > 0)
                );
    }
   
    //Get CurrentTS
    function getCurrentTimestamp() internal view returns (uint256) {
        return now;
    }

     //購買Token
    function buyTokens(address sender, uint256 value) internal {
        //Check Sale Status
        require(saleActive());
        
        //Minum buying limit
        require(value >= 0.5 ether);

        // Calculate token amount to be purchased
        uint256 bonus = getBonusByTime(getCurrentTimestamp());
        uint256 amount = value.mul(bonus);
        // 第一階段銷售期，每次購買量超過500Ether，多增加10%
        if (getCurrentTimestamp() >= startDate1 && getCurrentTimestamp() < endDate1) {
            uint256 p1Bouns = getBounsByAmount(value, amount);
            amount = amount + p1Bouns;
        }
        // We have enough token to sale
        require(saleCap >= amount);

        // Transfer
        balances[tokenWallet] = balances[tokenWallet].sub(amount);
        balances[sender] = balances[sender].add(amount);

        saleCap = saleCap - amount;

        // Update state.
        weiRaised = weiRaised + value;

        // Forward the fund to fund collection wallet.
        //tokenWallet.transfer(msg.value);
        fundWallet.transfer(msg.value);
    }   
}
/*Token  Contract*/
function buyTokens(address sender, uint256 value) internal {
    //Check Sale Status
    require(saleActive());
        
    //Minum buying limit
    require(value >= 0.5 ether);

    // Calculate token amount to be purchased
    uint256 bonus = getBonusByTime(getCurrentTimestamp());
    uint256 amount = value.mul(bonus);
    // 第一階段銷售期，每次購買量超過500Ether，多增加10%
    if (getCurrentTimestamp() >= startDate1 && getCurrentTimestamp() < endDate1) {
        uint256 p1Bouns = getBounsByAmount(value, amount);
        amount = amount + p1Bouns;
    }
    // We have enough token to sale
    require(saleCap >= amount);

    // Transfer
    balances[tokenWallet] = balances[tokenWallet].sub(amount);
    balances[sender] = balances[sender].add(amount);

    saleCap = saleCap - amount;

    // Update state.
    weiRaised = weiRaised + value;

    // Forward the fund to fund collection wallet.
    //tokenWallet.transfer(msg.value);
    fundWallet.transfer(msg.value);
}   

//購買Token