contract Slot is Ownable {
    using SafeMath for uint256;

    uint8   constant public SIZE =           100;        // size of the lottery
    uint32  constant public JACKPOT_CHANCE = 1000000;    // one in a million
    uint32  constant public INACTIVITY =     160000;     // blocks after which refunds can be claimed
    uint256 constant public PRICE =          100 finney;
    uint256 constant public JACK_DIST =      249 finney;
    uint256 constant public DIV_DIST =       249 finney;
    uint256 constant public GAS_REFUND =     2 finney;

    /* 
    *  every participant has an account index, the winners are picked from here
    *  all winners are picked in order from the single random int 
    *  needs to be cleared after every game
    */
    mapping (uint => mapping (uint => address)) public participants; // game number => counter => address
    SlotTicket public ticket; // this is a receipt for the ticket, it wont affect the prize distribution
    uint256 public jackpotAmount;
    uint256 public gameNumber;
    uint256 public gameStartedAt;
    address public fund; // address to send dividends
    uint256[8] public prizes = [4 ether, 
                                2 ether,
                                1 ether, 
                                500 finney, 
                                500 finney, 
                                500 finney, 
                                500 finney, 
                                500 finney];
    uint256 counter;

    event ParticipantAdded(address indexed _participant, uint256 indexed _game, uint256 indexed _number);
    event PrizeAwarded(uint256 indexed _game , address indexed _winner, uint256 indexed _amount);
    event JackpotAwarded(uint256 indexed _game, address indexed _winner, uint256 indexed _amount);
    event GameRefunded(uint256 _game);

    function Slot(address _fundAddress) payable { // address _ticketAddress
        // ticket = SlotTicket(_ticketAddress); // still need to change owner
        ticket = new SlotTicket();
        fund = _fundAddress;

        jackpotAmount = msg.value;
        gameNumber = 0;
        counter = 0;
        gameStartedAt = block.number;
    }

    function() payable {
        // fallback function to buy tickets
        buyTicketsFor(msg.sender);
    }

    function buyTicketsFor(address _beneficiary) public payable {
        require(_beneficiary != 0x0);
        require(msg.value >= PRICE);

        // calculate number of tickets, issue tokens and add participant
        // every (PRICE) buys a ticket, the rest is returned
        uint256 change = msg.value%PRICE;
        uint256 numberOfTickets = msg.value.sub(change).div(PRICE);
        ticket.mint(_beneficiary, numberOfTickets);
        addParticipant(_beneficiary, numberOfTickets);

        // Return change to msg.sender
        msg.sender.transfer(change);
    }

    /* private functions */

    function addParticipant(address _participant, uint256 _numberOfTickets) private {
        // if number of tickets exceeds the size of the game, tickets are added to next game

        for (uint256 i = 0; i < _numberOfTickets; i++) {
            // using gameNumber instead of counter/SIZE since games can be cancelled
            participants[gameNumber][counter%SIZE] = _participant; 
            ParticipantAdded(_participant, gameNumber, counter%SIZE);

            // msg.sender triggers the drawing of lots
            if (++counter%SIZE == 0) {
                awardPrizes();
                // Split the rest, increase game number
                distributeRemaining();
                increaseGame();
            }
            // loop continues if there are more tickets
        }
    }
    
    function awardPrizes() private {
        // get the winning number, no need to hash, since it is a deterministical function anyway
        uint256 winnerIndex = uint256(block.blockhash(block.number-1))%SIZE;

        // get jackpot winner, hash result of last two digit number (index) with 4 preceding zeroes will win
        uint256 jackpotNumber = uint256(block.blockhash(block.number-1))%JACKPOT_CHANCE;
        if (winnerIndex == jackpotNumber) {
            distributeJackpot(winnerIndex);
        }

        // loop throught the prizes 
        for (uint8 i = 0; i < prizes.length; i++) {
            // GAS: 21000 Paid for every transaction. (prizes.length)
            participants[gameNumber][winnerIndex%SIZE].transfer(prizes[i]); // msg.sender pays the gas, he's refunded later, % to wrap around
            PrizeAwarded(gameNumber, participants[gameNumber][winnerIndex%SIZE], prizes[i]);

            // increment index to the next winner to receive the next prize
            winnerIndex++;
        }
    }

    function distributeJackpot(uint256 _winnerIndex) private {
        uint256 amount = jackpotAmount;
        jackpotAmount = 0; // later on in the code sequence funds will be added

        participants[gameNumber][_winnerIndex].transfer(amount);
        JackpotAwarded(gameNumber,  participants[gameNumber][_winnerIndex], amount);
    }

    function distributeRemaining() private {
        // GAS: 21000 Paid for every transaction. (3)
        jackpotAmount = jackpotAmount.add(JACK_DIST);   // add to jackpot
        fund.transfer(DIV_DIST);                        // *cash register sound* dividends are paid to SLOT token owners
        msg.sender.transfer(GAS_REFUND);                // repay gas to msg.sender
    }

    function increaseGame() private {
        gameNumber++;
        gameStartedAt = block.number;
    }

    // public functions

    function spotsLeft() public constant returns (uint8 spots) {
        return SIZE - uint8(counter%SIZE);
    }

    function refundGameAfterLongInactivity() public {
        require(block.number.sub(gameStartedAt) >= INACTIVITY);
        require(counter%SIZE != 0); // nothing to refund
        // refunds for everybody can be requested after the game has gone (INACTIVITY) blocks without a conclusion
        
        // Checks-Effects-Interactions pattern to avoid re-entrancy
        uint256 _size = counter%SIZE; // not counter.size, but modulus of SIZE
        counter -= _size;

        for (uint8 i = 0; i < _size; i++) {
            // GAS: default 21000 paid for every transaction.
            participants[gameNumber][i].transfer(PRICE);
        }

        GameRefunded(gameNumber);
        increaseGame();
    }

    function destroy() public onlyOwner {
        require(jackpotAmount < 25 ether);

        // Transfer Ether funds to owner and terminate contract
        // It would be unfair to allow ourselves to destroy a contract with more than 25 ether and claim the jackpot,
        // lower than that we would consider it still a beta (any Ether would be transfered to the newer contract)

        ticket.destroy();
        selfdestruct(owner);
    }
    
    function changeTicketOwner(address _newOwner) public onlyOwner {
        // in case of new contract, old token can still be used
        // the token contract owner is the slot contract itself
        ticket.transferOwnership(_newOwner);
    }
    
    function changeFund(address _newFund) public onlyOwner {
        fund = _newFund;
    }
    
    function changeTicket(address _newTicket) public onlyOwner {
        ticket = SlotTicket(_newTicket); // still need to change owner to work
    }
}
/**  
 *  @title Slot
 *  @dev every participant has an account index, the winners are picked from here
 *  all winners are picked in order from the single random int 
 *  needs to be cleared after every game 
 */
function spotsLeft() public constant returns (uint8 spots) {
    return SIZE - uint8(counter%SIZE);
}

// public functions