#!/usr/bin/env node



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

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("c", { alias: "category", describe: "1 - product, 2 - standard", type: "string"})
  .option("i", { alias: "id", describe: "return question with id. use it with `seed` arg", type: "number"})

  .option("a", { alias: "add", describe: `pass json [{"q": "questionsPath", "a": "answersPath"}]. Paths are relative to dir`, type: "string"})
  .option("h", { alias: "human", describe: `human readable format`, type: "boolean"})
  .option("l", { alias: "list", describe: `generate lots of questions`, type: "number"})
  .argv;


let categoryFixed = false;
if(options.c)
  categoryFixed = true;

options.c = options.category = (parseInt(options.c)|0) || 1;






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"
];

var js = sources.map(a=>path.join(__dirname,'../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 = {}, localStorage = {getItem:()=>"{}"};'+js+'; return {quizGenerator, standardGenerator, initDataProvider, seeded: Math.random.seeded, rand}';


var ctx = new Function('',body)();

const rand = ctx.rand,
  seeded = ctx.seeded;
try{
  if( options.add )
    data.more = new Function('','return '+ options.add+';' )();
}catch(e){
  throw new Error(e)
}
//console.log(options);
data.after = function(inComeData, skipInit){
  if(inComeData){
    ctx.initDataProvider( data );
  }
  if(options.list && !skipInit){


    var c = options.list, origI = options.i|0;
    for(var i = 0; i< c; i++){
      options.i = origI+i;
      console.log(`Question `+(options.i+1));
      data.after(void 0, true);
      console.log('');

    }

    return;
  }

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

  let countStdQ = Object.values(data.standardQuestions).length;
  let state = {id: rand(1,countStdQ)};

  if(options.random){

    if(options.i){
      const quiz = [];

      let last = {}, cur, used = {};
      for( let i = 0; i < 100; i++ ){
        cur = {
          m: seeded() > 24 / ( 46 + 24 ),
          p: seeded() > 0.7,
          c: 1
        };

        if( last.c === 1 && seeded() > 0.5 ){
          cur = {
            c: 2
          };
          let id;
          do{
            id = rand(1, countStdQ);
          }while(id in used);

          used[id] = true;
          cur.id = id;

        }
        quiz.push(cur);
        last = cur;
      }
      if( options.seed )
        ctx.seeded.setStringSeed( options.i+options.seed );
      state = quiz[options.i];
      options.c = options.category =  quiz[options.i].c;
      if(options.c === 1){
        options.m = options.multiple = quiz[ options.i ].m;
        options.p = options.photo = quiz[ options.i ].p;
      }


    }else{
      options.m = options.multiple = seeded() > 24 / ( 46 + 24 );
      options.p = options.photo = seeded() > 0.7;
      options.c = options.category =seeded() > 0.6 ? 2 : 1;
    }
  }



  let result;
  if(options.category === 1){
    result = ctx.quizGenerator( options.multiple ? 'checkbox' : 'radio', options.photo );
  }else{
    result = ctx.standardGenerator(()=>state.id)
  }
  if(options.human){
    console.log(result.question)
    result.answers.forEach(a=>
      console.log( (result.type==='checkbox'?(a.correct?'[v]':'[ ]'):(a.correct?'(o)':'( )'))+ ' '+a.text)
    )
  }else{
    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()*/
/*

 */