#!/usr/bin/env node



const yargs = require("yargs"),
  fs = require('fs');

const options = yargs
  .usage("Usage: -n <name>")
  .option("r", { alias: "random", describe: "full random photo and multiple generator", type: "boolean"})
  .option("m", { alias: "multiple", describe: "multiple answers", type: "boolean"})
  .option("p", { alias: "photo", describe: "quiz with photo", type: "boolean"})
  .option("s", { alias: "seed", describe: "random seed", type: "string"})
  .option("o", { alias: "output", describe: "file for output", type: "string"})
  .option("v", { alias: "verbose", describe: "print log", type: "boolean"})
  .option("n", { alias: "nolog", describe: "no text log in object", type: "boolean"})
  .option("d", { alias: "dir", describe: "database dir", type: "string"})
  .option("f", { alias: "fake", describe: "add fake images", type: "boolean"})

  .argv;

const greeting = `Hello, ${options.name}!`;





const sources = [
  "js/releasable-observer.js",
  "js/pcg-base.js",
  "js/pcg-dom-util.js",

  "js/helpers/rand.js",

  "js/model/store.js",
  "js/model/data.js",

  "js/model/provider.js",
  "js/model/slice/productTable.js",

  "js/model/tag.js",
  "js/model/product.js",

  "js/helpers/textFilter.js",
  "js/helpers/answer.js",

  "js/controller/quizBits/main.js",

  "js/controller/quizGenerator.js",
  "js/controller/quizBits/checkbox.js",
  "js/controller/quizBits/checkboxPhoto.js",
  "js/controller/quizBits/radio.js",
  "js/controller/quizBits/radioPhoto.js"
];

const rand = function(a, b){
  if(Array.isArray(a)){
    return a[Math.random.seeded()*a.length|0];
  }
  if(typeof a === 'object' && 'max' in a){
    b = a.max;
    a = a.min || 0;
  }
  a = Math.ceil(a);
  b = Math.floor(b);
  return Math.floor(Math.random.seeded() * (b - a + 1)) + a;

  return (r-a)*(b-a)|0;
};

var js = sources.map(a=>'./public/'+a).map(n=>fs.readFileSync(n)+'').join('\n\n');

if(options.dir)
  process.env.KUS_DATA_DIR = options.dir;
const data = require("../db.js");
const body = 'const window = {};'+js+'; return {quizGenerator, initDataProvider, seeded: Math.random.seeded}';
var ctx = new Function('',body)();
//console.log(options);
data.after = function(){

  if( options.fake ){
    for(var i = 0; i < 10; i++){
      rand(Object.values(data.products)).image = 'https://robohash.org/'+Math.random().toString(36)
    }
  }
  ctx.initDataProvider( data );

  if( options.seed )
    ctx.seeded.setStringSeed( options.seed );

  const result = ctx.quizGenerator( options.multiple ? 'checkbox' : 'radio', options.photo );

  if( options.verbose ){
    console.log( result.log.join( '\n' ) )
  }else{
    if( options.nolog )
      delete result.log;
    console.log( '--- START ---\n\n' + JSON.stringify( result, null, 2 ) + '\n\n--- END ---' )
  }
  if( options.output )
    fs.writeFileSync( options.output, JSON.stringify( result, null, 2 ) )
};


//console.log(greeting);
/*const fs = require('fs');
fs.readFileSync()*/
/*

 */