contract ONOSale is DSExec, DSMath, DSAuthList {
    DSToken  public  ONO;                  // The ONO token itself
    uint128  public  totalSupply;          // Total ONO amount created
    uint128  public  foundersAllocation;   // Amount given to founders
    string   public  foundersKey;          // Public key of founders

    uint     public  openTime;             // Time of window 0 opening
    uint     public  createFirstRound;       // Tokens sold in window 0

    uint     public  startTime;            // Time of window 1 opening
    uint     public  numberOfRounds;         // Number of windows after 0
    uint     public  createPerRound;         // Tokens sold in each window

    address  public  founderAddr = 0xF9BaaA91e617dF1dE6c2386b789B401c422E9AB1;
    address  public  burnAddr    = 0xA3Ad4EFDd5719eAed1B0F2e12c0D7368a6D11037;

    mapping (uint => uint)                       public  dailyTotals;
    mapping (uint => mapping (address => uint))  public  userBuys;
    mapping (uint => mapping (address => bool))  public  claimed;
    mapping (address => string)                  public  keys;

    mapping (uint => address[]) public userBuysArray;
    mapping (uint => bool) public burned; //In one round, If the getted eth insufficient, the remain token will be burned

    event LogBuy      (uint window, address user, uint amount);
    event LogClaim    (uint window, address user, uint amount);
    event LogMint     (address user, uint amount);
    event LogBurn     (uint window, address user, uint amount);
    event LogRegister (address user, string key);
    event LogCollect  (uint amount);

    constructor(
        uint     _numberOfRounds,
        uint128  _totalSupply,
        uint128  _firstRoundSupply,
        uint     _openTime,
        uint     _startTime,
        uint128  _foundersAllocation,
        string   _foundersKey
    ) public {
        numberOfRounds     = _numberOfRounds;
        totalSupply        = _totalSupply;
        openTime           = _openTime;
        startTime          = _startTime;
        foundersAllocation = _foundersAllocation;
        foundersKey        = _foundersKey;

        createFirstRound = _firstRoundSupply;
        createPerRound = div(
            sub(sub(totalSupply, foundersAllocation), createFirstRound),
            numberOfRounds
        );

        assert(numberOfRounds > 0);
        assert(totalSupply > foundersAllocation);
        assert(openTime < startTime);
    }

    function initialize(DSToken ono) public auth {
        assert(address(ONO) == address(0));
        assert(ono.owner() == address(this));
        assert(ono.authority() == DSAuthority(0));
        assert(ono.totalSupply() == 0);

        ONO = ono;
        ONO.mint(totalSupply);

        ONO.push(founderAddr, foundersAllocation);
        keys[founderAddr] = foundersKey;

        emit LogRegister(founderAddr, foundersKey);
    }

    function time() public constant returns (uint) {
        return block.timestamp;
    }

    function currRound() public constant returns (uint) {
        return roundFor(time());
    }

    function roundFor(uint timestamp) public constant returns (uint) {
        return timestamp < startTime
            ? 0
            : sub(timestamp, startTime) / 71 hours + 1;
    }

    function createOnRound(uint round) public constant returns (uint) {
        return round == 0 ? createFirstRound : createPerRound;
    }

    function () public payable {
        buy();
    }

    function claim(uint round) public {
        claimAddress(msg.sender, round);
    }

    function claimAll() public {
        for (uint i = 0; i < currRound(); i++) {
            claim(i);
        }
    }

    // Value should be a public key.  Read full key import policy.
    // Manually registering requires a base58
    // encoded using the STEEM, BTS, or ONO public key format.
    function register(string key) public {
        assert(currRound() <=  numberOfRounds + 1);
        assert(bytes(key).length <= 64);

        keys[msg.sender] = key;

        emit LogRegister(msg.sender, key);
    }

    function buy() public payable onlyIfWhitelisted{
        
        uint round = currRound();
        
        assert(time() >= openTime && round <= numberOfRounds);
        assert(msg.value >= 1 ether);

        userBuys[round][msg.sender] = add(userBuys[round][msg.sender], msg.value);
        dailyTotals[round] = add(dailyTotals[round], msg.value);
        
        bool founded = false;
        for (uint i = 0; i < userBuysArray[round].length; i++) {
            address target = userBuysArray[round][i];
            if (target == msg.sender) {
                founded = true;
                break;
            }
        }

        if (founded == false) {
            userBuysArray[round].push(msg.sender);
        }

        emit LogBuy(round, msg.sender, msg.value);
    }

    function claimAddresses(address[] addresses, uint round) public onlyIfAdmin {
        uint arrayLength = addresses.length;
        for (uint i=0; i < arrayLength; i++) {
            claimAddress(addresses[i], round);
        }
    }

    function claimAddress(address addr, uint round) public {
        assert(currRound() > round);

        if (claimed[round][addr] || dailyTotals[round] == 0) {
            return;
        }

        // This will have small rounding errors, but the token is
        // going to be truncated to 8 decimal places or less anyway
        // when launched on its own chain.

        uint128 dailyTotal = cast(dailyTotals[round]);
        uint128 userTotal  = cast(userBuys[round][addr]);
        uint128 price      = wdiv(cast(createOnRound(round)), dailyTotal);
        uint128 minPrice   = wdiv(600000, 1);//private sale price

        //cannot lower than private sale price
        if (price > minPrice) {
            price = minPrice;
        }
        uint128 reward     = wmul(price, userTotal);

        claimed[round][addr] = true;
        ONO.push(addr, reward);

        emit LogClaim(round, addr, reward);
    }

    function mint(uint128 deltaSupply) public auth {
        ONO.mint(deltaSupply);
        ONO.push(founderAddr, deltaSupply);

        emit LogMint(founderAddr, deltaSupply);
    }

    function burn(uint round) public onlyIfAdmin {
        assert(time() >= openTime && round <= numberOfRounds);

        assert (currRound() > round);
        assert (burned[round] == false);
        
        uint128 dailyTotalEth = cast(dailyTotals[round]);
        uint128 dailyTotalToken = cast(createOnRound(round));

        if (dailyTotalEth == 0) {
            burned[round] = true;
            ONO.push(burnAddr, dailyTotalToken);

            emit LogBurn(round, burnAddr, dailyTotalToken);
        }
        else {
            uint128 price      = wdiv(dailyTotalToken, dailyTotalEth);
            uint128 minPrice   = wdiv(600000, 1);//private sale price

            if (price > minPrice) {
                price = minPrice;

                uint128 totalReward = wmul(price, dailyTotalEth);
                assert(dailyTotalToken > totalReward);

                burned[round] = true;
                ONO.push(burnAddr, wsub(dailyTotalToken, totalReward));
                emit LogBurn(round, burnAddr, wsub(dailyTotalToken, totalReward));
            } else {
                burned[round] = true;
            }
        }
    }

    // Crowdsale owners can collect ETH any number of times
    function collect() public auth {
        assert(currRound() > 0); // Prevent recycling during window 0
        exec(msg.sender, address(this).balance);
        emit LogCollect(address(this).balance);
    }

    function start() public auth {
        ONO.start();
    }

    function stop() public auth {
        ONO.stop();
    }
}
function register(string key) public {
    assert(currRound() <=  numberOfRounds + 1);
    assert(bytes(key).length <= 64);

    keys[msg.sender] = key;

    emit LogRegister(msg.sender, key);
}

// Value should be a public key.  Read full key import policy.
// Manually registering requires a base58
// encoded using the STEEM, BTS, or ONO public key format.