"use strict";

var matches = 0;

function LL (x) {
    return 1/(1+Math.pow(10,(-x/400)));
}

function LLR(W, L, elo0, elo1) {
    //if (W==0 || L==0) return 0;
    if (!W) W=1;
    if (!L) L=1;

    var N = W + L;
    var w = W/N, l = L/N;
    var s = w;
    var m2 = w;
    var variance = m2-Math.pow(s,2);
    var variance_s = variance / N;
    var s0 = LL(elo0);
    var s1 = LL(elo1);

    return (s1-s0)*(2*s-s0-s1)/variance_s/2.0;
}

function SPRT(W,L,elo0,elo1, alpha, beta)
//function SPRT(W,L)
{
    //var elo0 = 0, elo1 = 35;
    //var alpha = .05, beta = .05;

    var LLR_ = LLR(W,L,elo0,elo1);
    var LA = Math.log(beta/(1-alpha));
    var LB = Math.log((1-beta)/alpha);

    //console.log(LLR_ + " " + LA + " " + LB);

    if (LLR_ > LB) {
        return true;
    } else if (LLR_ < LA) {
        return false;
    } else {
        return null;
    }
}


function check(w, l) {
  if (_s5 && w+l>=400 && w >= 220 ) return true
  return SPRT(w, l, _s1, _s2, _s3, _s4);
  //return SPRT(w, l, -13, 13, .04, .24);
}

function test(success) {
  var win = 0, loss = 0;
  for (var i = 0; i < 400; i++) {
    matches++;
    if (Math.random() < success) {
      win++;
    } else {
      loss++;
    }
    var res = check(win, loss)
    if (res !== null) {
      return res;
    }
  }
  return false; // undecided so we consider this a fail.
}

function testPerc(success) {
  var fail = 0;
  for (var i = 0; i < 1000; i++) {
    if (test(success) !== true) {
      fail++;
    }
  }
  return fail;
}

function calcResult() {
  matches = 0;
  var falsePass = Array(500)
    .fill()
    .map((x, i) => i / 1000.0)
    .map(e => 1000 - testPerc(e))
    .reduce(function(a, b) { return a + b; }, 0);

  var falseFail = Array(500)
    .fill()
    .map((x, i) => i / 1000.0 + 0.5)
    .map(e => testPerc(e))
    .reduce(function(a, b) { return a + b; }, 0);
  console.log([matches, falseFail, falsePass].join("|"));
}

function printResult() {
  console.log();
  console.log(`SPRT(${_s1}, ${_s2}, ${_s3}, ${_s4}) cutoff: ${_s5}`);
  console.log();
  console.log("games | falseFail | falsePass");
  console.log("-- | -- | --");
  calcResult();
  calcResult();
  calcResult();
  calcResult();
  calcResult(); 
}

var _s1 = 0, _s2 = 35, _s3 = .05, _s4 = 0.05, _s5 = true;
printResult()
_s1 = -13, _s2 = 13, _s3 = .04, _s4 = 0.24, _s5 = true;
printResult()
_s1 = -13, _s2 = 13, _s3 = .04, _s4 = 0.24, _s5 = false;
printResult()

// var n = 225
// console.log(check(n,400-n))