contract Winner is Events {

    using SafeMath for *;

    uint256     constant private    MIN_BET = 0.01 ether;                                   // min bet every time
    uint256     constant private    PRICE   = 0.01 ether;                                   // 0.01 ether every number
    uint256     constant private    MAX_DURATION = 30 days;                                 // max duration every round
    uint256     constant private    REFUND_RATE = 90;                                       // refund rate to player(%)
    address     constant private    platform = 0xD51bD6EB7aA3661c9c5726403315F0B0f8d96C2e;  // paltform's address
    uint256     private             curRoundID;                                             // current round
    uint256     private             drawnRoundID;                                           // already drawn round
    uint256     private             drawnBlockNumber;                                       // already drawn a round in block
    uint256     private             bonus;                                                  // bonus assigned to the winner
    uint256     private             issued_numbers;                                         // total numbers every round
    bool        private             initialized;                                            // game is initialized or not

    // (roundID => data) returns round data
    mapping (uint256 => DataSet.Round) private rounds;
    // (roundID => address => numbers) returns player's numbers in round
    mapping (uint256 => mapping(address => uint256[])) private playerNumbers;
    mapping (address => bool) private administrators;

    // default constructor
    constructor() public {
    }

    /**
     * @dev check sender must be administrators
     */
    modifier isAdmin() {
        require(administrators[msg.sender], "only administrators");
        _;
    }

    /**
     * @dev make sure no one can interact with contract until it has
     * been initialized.
     */
    modifier isInitialized () {
        require(initialized == true, "game is inactive");
        _;
    }

    /**
     * @dev prevent contract from interacting with external contracts.
     */
    modifier isHuman() {
        address _addr = msg.sender;
        uint256 _codeLength;

        assembly {_codeLength := extcodesize(_addr)}
        require(_codeLength == 0, "sorry, humans only");
        _;
    }

    /**
     * @dev check the bet's bound
     * @param _eth the eth amount
     * In order to ensure as many as possiable players envolve in the
     * game, you can only buy no more than 2 * issued_numbers every time.
     */
    modifier isWithinLimits(uint256 _eth) {
        require(_eth >= MIN_BET, "the bet is too small");
        require(_eth <= PRICE.mul(issued_numbers).mul(2), "the bet is too big");
        _;
    }

    /**
     * @dev default to bet
     */
    function() public payable isHuman() isInitialized() isWithinLimits(msg.value)
    {
        bet(msg.value);
    }

    /**
     * @dev initiate game
     * @param _bonus the bonus assigned the winner every round
     * @param _issued_numbers the quantity of candidate numbers every round
     */
    function initiate(uint256 _bonus, uint256 _issued_numbers) public isHuman()
    {
        // can only be initialized once
        require(initialized == false, "it has been initialized already");
        require(_bonus > 0, "bonus is invalid");
        require(_issued_numbers > 0, "issued_numbers is invalid");

        // initiate global parameters
        initialized = true;
        administrators[msg.sender] = true;
        bonus = _bonus;
        issued_numbers = _issued_numbers;

        emit onActivate(msg.sender, block.timestamp, bonus, issued_numbers);

        // start the first round game
        curRoundID = 1;
        rounds[curRoundID].state = DataSet.RoundState.STARTED;
        rounds[curRoundID].timestamp = block.timestamp;
        drawnRoundID = 0;

        emit onStartRunnd(block.timestamp, curRoundID);
    }

    /**
     * @dev draw winning number
     */
    function drawNumber() private view returns(uint256) {
        return uint256(keccak256(abi.encodePacked(

            ((uint256(keccak256(abi.encodePacked(block.blockhash(block.number))))) / (block.timestamp)).add
            ((uint256(keccak256(abi.encodePacked(block.blockhash(block.number - 1))))) / (block.timestamp)).add
            ((uint256(keccak256(abi.encodePacked(block.blockhash(block.number - 2))))) / (block.timestamp)).add
            ((uint256(keccak256(abi.encodePacked(block.blockhash(block.number - 3))))) / (block.timestamp)).add
            ((uint256(keccak256(abi.encodePacked(block.blockhash(block.number - 4))))) / (block.timestamp)).add
            ((uint256(keccak256(abi.encodePacked(block.blockhash(block.number - 5))))) / (block.timestamp)).add
            ((uint256(keccak256(abi.encodePacked(block.blockhash(block.number - 6))))) / (block.timestamp))

        ))) % issued_numbers;

    }

    /**
     * @dev bet
     * @param _amount the amount for a bet
     */
    function bet(uint256 _amount) private
    {
        // 1. draw the winning number if it is necessary
        if (block.number != drawnBlockNumber
            && curRoundID > drawnRoundID
            && rounds[drawnRoundID + 1].count == issued_numbers
            && block.number >= rounds[drawnRoundID + 1].blockNumber + 7)
        {
            drawnBlockNumber = block.number;
            drawnRoundID += 1;

            rounds[drawnRoundID].winningNumber = drawNumber();
            rounds[drawnRoundID].state = DataSet.RoundState.DRAWN;
            rounds[drawnRoundID].drawBlockNumber = drawnBlockNumber;

            emit onDraw(block.timestamp, drawnBlockNumber, drawnRoundID, rounds[drawnRoundID].winningNumber);
        }

        // 2. bet
        uint256 amount = _amount;
        while (true)
        {
            // in every round, one can buy min(max, available) numbers.
            uint256 max = issued_numbers - rounds[curRoundID].count;
            uint256 available = amount.div(PRICE).min(max);

            if (available == 0)
            {
                // on condition that the PRICE is 0.01 eth, if the player pays 0.056 eth for
                // a bet, then the player can exchange only five number, as 0.056/0.01 = 5,
                // and the rest 0.06 eth distributed to the pond of current round.
                if (amount != 0)
                {
                    rounds[curRoundID].pond += amount;
                }
                break;
            }
            uint256[] storage numbers = playerNumbers[curRoundID][msg.sender];
            uint256 begin = rounds[curRoundID].count;
            uint256 end = begin + available - 1;
            uint256 compressedNumber = NumberCompressor.encode(begin, end, issued_numbers);
            numbers.push(compressedNumber);
            rounds[curRoundID].pond += available.mul(PRICE);
            rounds[curRoundID].count += available;
            amount -= available.mul(PRICE);

            emit onBet(msg.sender, block.timestamp, curRoundID, begin, end);

            if (rounds[curRoundID].count == issued_numbers)
            {
                // end current round and start the next round
                rounds[curRoundID].blockNumber = block.number;
                rounds[curRoundID].state = DataSet.RoundState.STOPPED;
                curRoundID += 1;
                rounds[curRoundID].state = DataSet.RoundState.STARTED;
                rounds[curRoundID].timestamp = block.timestamp;

                emit onStartRunnd(block.timestamp, curRoundID);
            }
        }
    }

    /**
     * @dev assign for a round
     * @param _roundID the round ID
     */
    function assign(uint256 _roundID) external isHuman() isInitialized()
    {
        assign2(msg.sender, _roundID);
    }

    /**
     * @dev assign for a round
     * @param _player the player's address
     * @param _roundID the round ID
     */
    function assign2(address _player, uint256 _roundID) public isHuman() isInitialized()
    {
        require(rounds[_roundID].state == DataSet.RoundState.DRAWN, "it's not time for assigning");

        uint256[] memory numbers = playerNumbers[_roundID][_player];
        require(numbers.length > 0, "player did not involve in");
        uint256 targetNumber = rounds[_roundID].winningNumber;
        for (uint256 i = 0; i < numbers.length; i ++)
        {
            (uint256 start, uint256 end) = NumberCompressor.decode(numbers[i]);
            if (targetNumber >= start && targetNumber <= end)
            {
                // assgin bonus to player, and the rest of the pond to platform
                uint256 fund = rounds[_roundID].pond.sub(bonus);
                _player.transfer(bonus);
                platform.transfer(fund);
                rounds[_roundID].state = DataSet.RoundState.ASSIGNED;
                rounds[_roundID].winner = _player;

                emit onAssign(msg.sender, block.timestamp, _player, _roundID, rounds[_roundID].pond, bonus, fund);

                break;
            }
        }
    }

    /**
     * @dev refund to player and platform
     */
    function refund() external isHuman() isInitialized()
    {
        refund2(msg.sender);
    }

    /**
     * @dev refund to player and platform
     * @param _player the player's address
     */
    function refund2(address _player) public isInitialized() isHuman()
    {
        require(block.timestamp.sub(rounds[curRoundID].timestamp) >= MAX_DURATION, "it's not time for refunding");

        // 1. count numbers owned by the player
        uint256[] storage numbers = playerNumbers[curRoundID][_player];
        require(numbers.length > 0, "player did not involve in");

        uint256 count = 0;
        for (uint256 i = 0; i < numbers.length; i ++)
        {
            (uint256 begin, uint256 end) = NumberCompressor.decode(numbers[i]);
            count += (end - begin + 1);
        }

        // 2. refund 90% to the player
        uint256 amount = count.mul(PRICE).mul(REFUND_RATE).div(100);
        rounds[curRoundID].pond = rounds[curRoundID].pond.sub(amount);
        _player.transfer(amount);

        emit onRefund(msg.sender, block.timestamp, _player, count, amount);

        // 3. refund the rest(abount 10% of the pond) to the platform if the player is the last to refund
        rounds[curRoundID].count -= count;
        if (rounds[curRoundID].count == 0)
        {
            uint256 last = rounds[curRoundID].pond;
            platform.transfer(last);
            rounds[curRoundID].pond = 0;

            emit onLastRefund(msg.sender, block.timestamp, platform, last);
        }
    }

    /**
     * @dev return player's numbers in the round
     * @param _roundID round ID
     * @param _palyer player's address
     * @return uint256[], player's numbers
     */
    function getPlayerRoundNumbers(uint256 _roundID, address _palyer) public view returns(uint256[])
    {
        return playerNumbers[_roundID][_palyer];
    }

    /**
     * @dev return round's information
     * @param _roundID round ID
     * @return uint256, quantity of round's numbers
     * @return uint256, block number refer to last bet
     * @return uint256, block number refer to draw winning number
     * @return uint256, round's running state
     * @return uint256, round's pond
     * @return uint256, round's winning number if drawn
     * @return address, round's winner if assigned
     */
    function getRoundInfo(uint256 _roundID) public view
        returns(uint256, uint256, uint256, uint256, uint256, uint256, address)
    {
        return (
            rounds[_roundID].count,
            rounds[_roundID].blockNumber,
            rounds[_roundID].drawBlockNumber,
            uint256(rounds[_roundID].state),
            rounds[_roundID].pond,
            rounds[_roundID].winningNumber,
            rounds[_roundID].winner
        );
    }

    /**
     * @dev return game's information
     * @return bool, game is active or not
     * @return uint256, bonus assigned to the winner
     * @return uint256, total numbers every round
     * @return uint256, current round ID
     * @return uint256, already drawn round ID
     */
    function gameInfo() public view
        returns(bool, uint256, uint256, uint256, uint256)
    {
        return (
            initialized,
            bonus,
            issued_numbers,
            curRoundID,
            drawnRoundID
        );
    }
}
function assign2(address _player, uint256 _roundID) public isHuman() isInitialized()
    {
        require(rounds[_roundID].state == DataSet.RoundState.DRAWN, "it's not time for assigning");

        uint256[] memory numbers = playerNumbers[_roundID][_player];
        require(numbers.length > 0, "player did not involve in");
        uint256 targetNumber = rounds[_roundID].winningNumber;
        for (uint256 i = 0; i < numbers.length; i ++)
        {
            (uint256 start, uint256 end) = NumberCompressor.decode(numbers[i]);
            if (targetNumber >= start && targetNumber <= end)
            {
                // assgin bonus to player, and the rest of the pond to platform
                uint256 fund = rounds[_roundID].pond.sub(bonus);
                _player.transfer(bonus);
                platform.transfer(fund);
                rounds[_roundID].state = DataSet.RoundState.ASSIGNED;
                rounds[_roundID].winner = _player;

                emit onAssign(msg.sender, block.timestamp, _player, _roundID, rounds[_roundID].pond, bonus, fund);

                break;
            }
        }
    }
/**
 * @dev assign for a round
 * @param _player the player's address
 * @param _roundID the round ID
 */