const lapk = (text)=>`„${text}“`;
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;
  },
  probabilityRand = function(items) {
    let sum = 0;
    for( let i = 0, _i = items.length; i < _i; i++ ){
      const item = items[ i ];
      sum += item.probability |0;
    }
    const theRandom = Math.random.seeded();
    let total = 0;

    for( let i = 0, _i = items.length; i < _i; i++ ){
      const item = items[ i ];
      total += item.probability/sum;
      if(theRandom < total)
        return item;
    }
  };

const normalizeText = function(text) {
  return text.trim().toLowerCase().replace(/[^а-я]/g,'').replace(/[аоуеэюёиыя]+/g,'о')
};

const quizTypes = {
  checkbox: [],
  checkboxPhoto: {

  },
  radio: [],
  radioPhoto: {

  }
};
const shuffle = function (a) {
  for (let i = a.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random.seeded() * (i + 1));
    [a[i], a[j]] = [a[j], a[i]];
  }
  return a;
};
const standardGenerator = function(random) {
  const initialSeed = Math.random.seeded.getStringSeed();
  const log = quizGenerator.log = ['Random seed: '+initialSeed];
  const questionID = random(Object.values(dP.standardQuestions)),
        q = dP.standardQuestions[questionID];
  log.push('Creating standard question.');
  log.push('It would be question number '+questionID);
  log.push('');
  log.push('Title '+q.title);
  q.answers.forEach(
    a =>
      log.push((a.correct?'+':' ')+` > ${a.title}`));
  return {
    type: q.multiple ? 'checkbox': 'radio',
    categoryId: 2,
    productId: q.cardInfoID,
    question: textFormat(q.title),
    answers: shuffle(q.answers.map(a =>
      a.correct ?
        new Answer.Correct(a.title) :
        new Answer.Wrong(a.title))),

    image: !q.image?null:q.image,
    log
  };
};
const quizGenerator = function(type, photo, subType) {
    return _quizGenerator(type, photo, subType);
  },
  _quizGenerator = function(type, photo, subType, attempt) {
    attempt = attempt || 0;
    const initialSeed = Math.random.seeded.getStringSeed();
    let log;
    if(attempt === 0){
      const types = quizTypes[type+(photo?'Photo':'')];
      subType = probabilityRand(types);
      log = quizGenerator.log = ['Random seed: '+initialSeed,'Quiz generate '+type+(photo ? ' with photo':'') +' '+(subType?`${lapk(subType.type)}`:'. FAIL')];
    }else if(attempt<30){
      log = quizGenerator.log;
      log.push('\nATTEMPT FAILED!\n\n'+
        '------------------------\n' +
        '   ATTEMPT '+ (attempt+1)+'\n'+
        '------------------------\n\n'
      )
    }else{
      throw new Error('Too much errors')
    }



    const cfg = subType;


    if(!cfg)
      return {answers: [], log};
    const source = cfg.from.call(cfg, log);
    if(source === false){
      // давай по новой
      return _quizGenerator( type, photo, subType, attempt + 1 );
    }

    let answers = shuffle(cfg.answer.call(cfg, source, log));
    if(answers === false){
      // давай по новой
      return _quizGenerator( type, photo, subType, attempt + 1 );
    }
    return {
      seed: initialSeed,
      type,
      categoryId: 1,
      productId: source.baseProduct.id,
      question: cfg.question.call(cfg, source, log),
      answers,
      image: !photo?null:source.baseProduct.image,

      log,

    }
  };
