import { assert } from 'meteor/practicalmeteor:chai';

var syncTimeout,functionList=[];
function syncFunction(newFunction,time) {
  function newTimeout() {
    let x = functionList.pop();
    syncTimeout=setTimeout(function() {
      x.func();
      syncTimeout=undefined;
      if(functionList.length>0) newTimeout();
    },x.time);
  }
  functionList.push({func:newFunction,time:time});
  if(!syncTimeout) newTimeout();
}
var count=0,timeoutTime=0;
export function createUser(userId,done,debug=false) {
  count++;
  obj = Users[userId];
  Meteor.logout();
  Meteor.flush();
  subscribers();
  if(count>3) {
    timeoutTime=1500;
    if(debug) console.log("CreateUser: slow down for 1,5sec.");
  }
  syncFunction(function() {
    SecureLayer.user.login(obj.username,obj.password, function(err) {
      if(debug) console.log(err);
      if(err) {
        SecureLayer.user.create(obj,function(err1) {
          if(debug) console.log(err1);
          assert.equal(err1,undefined);
          if(err1==undefined) {
            Users[userId]._id=Meteor.userId();
            done(false,true);
          }
        });
      } else {
        Users[userId]._id=Meteor.userId();
        done(false,false);
      }
    });
  },timeoutTime);
}

export function subscribers() 

export var Users = {
  user1: {
    username: "test1",
    email : "test@test.de",
    password : 'password!1',
  },
  user2: {
    username: "test2",
    email : "test2@test.de",
    password : 'password!2',
  },
  user3: {
    username: "test3",
    email : "test3@test.de",
    password : 'password!3',
  },
  user4: {
    username: "test4",
    email : "test4@test.de",
    password : 'password!4',
  },
};

export function defaultCheckCollectionsData(collection,docId,debug=false) {
  let encrypted = collection.findOne({_id:docId},{transform:null});
  let decrypted = collection.findOne({_id:docId});
  let local = collection.local.findOne({_id:docId});
  if(debug) console.log(encrypted,decrypted,local);

  assert.equal(encrypted.encrypted,true);
  assert.equal(encrypted.nonSecure,decrypted.nonSecure);

  assert.equal(local.secure1,decrypted.secure1);

  assert.equal(decrypted.encrypted,false);
  assert.notEqual(encrypted.secure1,decrypted.secure1);
  assert.notEqual(local.secure1,encrypted.secure1);


  //trivial?
  assert.equal(encrypted.transform1,undefined);
  assert.equal(encrypted.transform2,undefined);

  //check "normal" transform
  assert.equal(decrypted.transform1,true);
  assert.equal(decrypted.transform2,undefined);

  //check after (local) transform
  assert.equal(local.transform1,true);
  assert.equal(local.transform2,true);

  return {
    encrypted: encrypted,
    decrypted: decrypted,
    local: local,
  }
}

{
  Meteor.subscribe('db_secure_groups_users');
  Meteor.subscribe('db_users');
  Meteor.subscribe('db_secure_user');

  Meteor.subscribe('db_secure_collection_test');
}