const bcrypt = require('bcrypt');
const shuffle = require('knuth-shuffle-seeded');
const saltRounds = 10;
const seed = require('seedrandom');
var fs = require('fs');
var csvsync = require('csvsync');

const drawing = require('./seed.json');
const salt = drawing.seed;
const validation_string = drawing.validation_string;


console.log("Validating salt with bcrypt");
console.log("Validation string: " + validation_string);
console.log("Salt:" + salt);
let signature = bcrypt.hashSync(validation_string, salt);
console.log("Computed signature:" + signature);
//
// 'entries' is our list of valid entries ordered by time of stake
// 
var csv = fs.readFileSync('./entries.csv');
var entries = csvsync.parse(csv, {
    returnObject: true,
});
console.log("Number of entries:" + entries.length);

//
// Initial random number generator with published seed
//
var myrng = seed(salt);

// 
// Shuffle the entries using knuth-shuffle-seeded
// 
var shuffle_entries = [...entries]; // Clone the array
shuffle_entries = shuffle(shuffle_entries, salt);
let shuffle_postion = 0;
shuffle_entries.forEach(object => {
    object.shuffle_postion = shuffle_postion++;
});

console.log("Number of shuffled entries:" + shuffle_entries.length);

//
// Do 50 winning drawings, skipping wallets that already won once
//
let winning_entries = [];
let win_count = 0;
let winning_wallet_tracker = [];
let drawing_number = 0;
while (win_count < 50) {
    let drawing_value = myrng();
    let winning_entry = Math.floor(drawing_value * shuffle_entries.length)

    if (winning_wallet_tracker.includes(shuffle_entries[winning_entry].wallet)) {
        shuffle_entries[winning_entry].duplicate_draw = true;
        console.log(`Drawing:${drawing_number} - SKIPPING DUPLICATE WINNER${winning_entry}`);
    } else {
        shuffle_entries[winning_entry].duplicate_draw = false;
        console.log(`Drawing:${drawing_number} - winning entry ${winning_entry}`);
        win_count++;
    }
    winning_wallet_tracker.push(shuffle_entries[winning_entry].wallet);
    winning_entries.push(shuffle_entries[winning_entry]);
    drawing_number++;
}