contract Grail is Ownable {

    struct RaffleEntry {
        address user;
        uint32 count;
    }

    // Interfaces to interact with the other contracts
    InterfaceRainbows public Rainbows;

    // address[] public entryList;
    address[] public winnerList;

    uint256 public raffleEntryCost = 20 ether;

    // Entry time.
    uint256 public raffleStartTime = 0;
    uint256 public raffleEndTime = 0;

    RaffleEntry[] public raffleEntries;
    uint256 public totalRaffleEntries;

    uint256 public uniqueEntryAddresses;
    mapping(address => uint256) public userEntries;
    mapping(address => bool) public winners;

    event RaffleWinner(address indexed _winner);

    // Extended access
    mapping(address => bool) public extendedAccess;

    modifier raffleEnabled() {
        require(raffleStartTime > 0 && block.timestamp > raffleStartTime, "Raffle not started.");
        require(raffleEndTime > 0 && block.timestamp <= raffleEndTime, "Raffle has ended.");
        _;
    }

    modifier onlyFromRestricted() {
        require(extendedAccess[msg.sender], "Your address does not have permission to use.");
        _;
    }

    constructor() {
        extendedAccess[msg.sender] = true;
    }

    // Set the address for the contract.
    function setAddressAccess(address _noundles, bool _value) public onlyOwner {
        extendedAccess[_noundles] = _value;
    }

    // Get the access status for a address.
    function getAddressAccess(address user) external view returns(bool) {
        return extendedAccess[user];
    }

    // Reset the raffle.
    function resetRaffle() public onlyFromRestricted {
        totalRaffleEntries = 0;
        uniqueEntryAddresses = 0;
        for(uint i; i < raffleEntries.length; i++) {
            address user = raffleEntries[i].user;
            userEntries[user] = 0;
            winners[user] = false;
        }
        delete winnerList;
        delete raffleEntries;
    }

    function resetWinners() internal {
        for(uint i; i < raffleEntries.length; i++) {
            address user = raffleEntries[i].user;
            winners[user] = false;
        }
        delete winnerList;
    }

    // Set the time.
    function setRaffleSettings(uint256 _raffleStartTime, uint256 _raffleEndTime, uint256 _raffleEntryCost) public onlyFromRestricted {
        raffleStartTime = _raffleStartTime;
        raffleEndTime   = _raffleEndTime;
        raffleEntryCost = _raffleEntryCost;
    }

    // Set the address.
    function setAddresses(address _rainbow) external onlyOwner {
        Rainbows = InterfaceRainbows(_rainbow);
    }

    // Enter the raffle.
    function enterRaffle(uint32 _entryCount) public raffleEnabled {
        Rainbows.burn(msg.sender, raffleEntryCost * _entryCount);

        raffleEntries.push(RaffleEntry(msg.sender, _entryCount));
        totalRaffleEntries += _entryCount;

        if(userEntries[msg.sender] == 0) {
            uniqueEntryAddresses += 1;
        }

        userEntries[msg.sender] += _entryCount;
    }

    // Pick the winners.
    function pickWinners(uint256 _winnerCount) public onlyFromRestricted {
        require(_winnerCount <= uniqueEntryAddresses, "Can't have more winners than entries");

        // Reset the winners.
        resetWinners();

        uint256 retryCounter = 0;

        for(uint256 i = 1; i < (_winnerCount + 1); i += 1) {

            uint256 pick = getRandomNumber(i + retryCounter) % totalRaffleEntries;
            uint256 runningTotal = 0;

            for(uint r; r < raffleEntries.length; r += 1) {

                RaffleEntry storage entry = raffleEntries[r];

                if(runningTotal <= pick && pick < (runningTotal + entry.count)) {

                    // If it's already picked.
                    if(winners[entry.user]) {
                        i--;
                        retryCounter += 1;
                        break;
                    }

                    winners[entry.user] = true;
                    emit RaffleWinner(entry.user);
                    winnerList.push(entry.user);
                    break;
                }

                // Add to our total.
                runningTotal += entry.count;
            }
        }
    }

    function pickWinnersView(uint256 _winnerCount) public view returns (address [] memory){
        require(_winnerCount <= uniqueEntryAddresses, "Can't have more winners than entries");

        address[] memory localWinnerList = new address[](_winnerCount);

        uint256 retryCounter = 0;

        for(uint256 i = 1; i < (_winnerCount + 1); i += 1) {

            uint256 pick = getRandomNumber(i + retryCounter) % totalRaffleEntries;
            uint256 runningTotal = 0;

            for(uint r; r < raffleEntries.length; r += 1) {
                RaffleEntry storage entry = raffleEntries[r];

                if(runningTotal <= pick && pick < (runningTotal + entry.count)) {
                    localWinnerList[i -1] = entry.user;
                    break;
                }

                // Add to our total.
                runningTotal += entry.count;
            }
        }

        return localWinnerList;
    }

    function getRandomNumber(uint256 _arg) public view returns (uint) {
        return uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp, _arg)));
    }

    function getEntryCount(address _arg) public view returns (uint256) {
        return userEntries[_arg];
    }

    function getWinners() public view returns (address[] memory) {
        return winnerList;
    }

    function checkWinners(address _arg) public view returns (bool) {
        return winners[_arg];
    }
}
function enterRaffle(uint32 _entryCount) public raffleEnabled {
    Rainbows.burn(msg.sender, raffleEntryCost * _entryCount);

    raffleEntries.push(RaffleEntry(msg.sender, _entryCount));
    totalRaffleEntries += _entryCount;

    if(userEntries[msg.sender] == 0) {
        uniqueEntryAddresses += 1;
    }

    userEntries[msg.sender] += _entryCount;
}

// Enter the raffle.