//const page=CONFIG("logopage");
const dbase=CONFIG("dbaseA");
const conURL=CONFIG("conURLA");



exports.install = function() {

	// Enable cors
	//CORS();
//['authorize','@administrator','@https','@administrator']
	ROUTE('mongo/collection/create/{name}',create_collections,['authorize','@administrator']); // 2 MB
	ROUTE('mongo/collections/createcode',creat_CODEcollections,['post','authorize','@administrator']); // 2 MB
//	ROUTE('mongo/collection/create/',view_CRTcollections,['authorize','@administrator']); // 2 MB
//	ROUTE('mongo/collection/create',view_CRTcollections,['post','authorize','@administrator']); // 2 MB






	ROUTE('mongo/collections/list',view_LSTcollections,['authorize','@administrator']); // 2 MB
	ROUTE('mongo/collection/delete',get_DELcollection,['ajax','get','authorize','@administrator']); // 2 MB
	ROUTE('mongo/collection/empty',get_EMPTYcollection,['ajax','get','authorize','@administrator']); // 2 MB
	ROUTE('mongo/collection/import/{name}',view_IMPORTcollection,['authorize','@administrator']); // 2 MB
	ROUTE('mongo/collection/import/{name}',post_IMPORTcollection,['post','authorize','@administrator']); // 2 MB	
	ROUTE('mongo/collection/export/{name}',view_EXPORTcollection,['authorize','@administrator']); // 2 MB

	
	
	
	
	ROUTE('mongo/collection/list/{name}/{num}',view_LSTcollection,['authorize','@administrator']); // 2 MB
	ROUTE('mongo/collection/record/delete',DELrecord,['ajax','get','authorize','@administrator']); // 2 MB	
	ROUTE('mongo/collection/bulk/delete',DELbulk,['ajax','post','upload','authorize','@administrator',10000],2048); // 2 MB	
	ROUTE('mongo/collection/update/{name}/{id}',view_UPDcollection,['authorize','@administrator']); // 2 MB
	ROUTE('mongo/collection/update/{name}/{id}',post_UPDcollection,['post','upload','authorize','@administrator',10000],2048); // 2 MB
	ROUTE('mongo/collection/insertOne/{name}',view_INScollectionO,['authorize','@administrator']); // 2 MB
	ROUTE('mongo/collection/insertOne/{name}',post_INScollectionO,['post','authorize','@administrator']); // 2 MB
	ROUTE('mongo/collection/insertMany/{name}',view_INScollectionM,['authorize','@administrator']); // 2 MB
	ROUTE('mongo/collection/insertMany/{name}',post_INScollectionM,['post','authorize','@administrator']); // 2 MB
	ROUTE('mongo/collection/insertFile/{name}',view_INScollectionF,['authorize','@administrator']); // 2 MB
	ROUTE('mongo/collection/insertFile/{name}',post_INScollectionF,['post','authorize','@administrator']); // 2 MB


}




async function create_collections(req,res){
	var self = this;
	let col=decodeURI(self.params.name);
	const mongo=MODULE('https_modules/HmongoDBpro');
	const con=await mongo.connfull(conURL);
	var model= await mongo.creat(con.data,dbase,col);
	self.redirect('/mongo/collections/list');
}

async function creat_CODEcollections(req,res){
	var self = this,setobj=[],body=self.req.body,k;
 	const valid=MODULE('https_modules/Hvalidation');
    setobj=await valid.setVALUE(body.import.replace(/\\r\\n/g,""),"isarray");
	const mongo=MODULE('https_modules/HmongoDB');
	const con=await mongo.connfull(conURL);
	var model=await mongo.insertFULL(con.data,dbase,body.cname,setobj);    
	self.redirect('/mongo/collection/list/'+body.cname+'/1');
    
}



async function view_LSTcollections(req, res) {
    var self = this;
	const mongopro=MODULE('https_modules/HmongoDBpro');
	const con=await mongopro.connfull(conURL);
	var model=await mongopro.DBlist(con.data,dbase);
	  self.layout('~../modules/https_modules/viewpartial/mongodb/mongopanel');
	self.view('~../modules/https_modules/viewpartial/mongodb/home',model.data);
}

async function get_DELcollection(req,res){
	var self = this;
	var query=self.req.query
	const mongo=MODULE('https_modules/HmongoDBpro');
	const con=await mongo.connfull(conURL);
	var model= await mongo.delete(con.data,dbase,query["collection"]);
	model.name=query["collection"];
	model['data']=F.resource(model.status);
    self.status=200;
    self.json(model);
}
async function get_EMPTYcollection(req,res){
	var self = this;
	var query=self.req.query
	const mongo=MODULE('https_modules/HmongoDBpro');
	const con=await mongo.connfull(conURL);
	var model= await mongo.empty(con.data,dbase,query["collection"]);
	model.name=query["collection"];
	model['data']=F.resource(model.status);
    self.status=200;
    self.json(model);
}


//	ROUTE('mongo/collection/import/',view_IMPORTcollection,['ajax','get','authorize','@administrator']); // 2 MB
//	ROUTE('mongo/collection/export',view_EXPORTcollection,['ajax','get','authorize','@administrator']); // 2 MB

async function view_IMPORTcollection(req,res){
	var self = this;
	var model={collection:decodeURI(self.params.name)};
    self.layout('~../modules/https_modules/viewpartial/mongodb/mongopanel');
	self.view('~../modules/https_modules/viewpartial/mongodb/import',model);
}
async function post_IMPORTcollection(req,res){
	var self = this,setobj=[],arr=[],body=self.req.body,k,obj={ insertOne: { '"document"': {}}};
 	const valid=MODULE('https_modules/Hvalidation');
	let col=decodeURI(self.params.name);
	if(body.import.length>0){
	    setobj=await valid.setVALUE(body.import.replace(/\\r\\n/g,""),"isarray");
	    const mongo=MODULE('https_modules/HmongoDBpro');
    	const con=await mongo.connfull(conURL);
    	var model=await mongo.import(con.data,dbase,col,setobj);    
	}
	self.redirect('/mongo/collection/list/'+col);
}


async function view_EXPORTcollection(req,res){
	var self = this,col=decodeURI(self.params.name);
	const mongo=MODULE('https_modules/HmongoDB');
	const con=await mongo.connfull(conURL);
	var model=await mongo.findfull(con.data,dbase,col); 
	model.collection=col;
    self.layout('~../modules/https_modules/viewpartial/mongodb/mongopanel');
	self.view('~../modules/https_modules/viewpartial/mongodb/export',model);
}







async function view_LSTcollection(req,res){
	var self = this;
	let limit=50,col=decodeURI(self.params.name);
	const mongo=MODULE('https_modules/HmongoDB');
	console.log(decodeURI(self.params.name));
	
	const con=await mongo.connfull(conURL);
		var model=await mongo.findfull(con.data,dbase,col,{},{yo:0},{},(self.params.num-1)*limit,limit);
		model.total=await mongo.counter(con.data,dbase,col);
model.collection=col;

	model=await FUNC.paging(model.total,self.params.num,limit,self.url,model,"/mongo/collection/show/"+col+"/{0}");	
	
	
	  self.layout('~../modules/https_modules/viewpartial/mongodb/mongopanel');
	self.view('~../modules/https_modules/viewpartial/mongodb/show',model);
}
async function DELrecord(req,res){
	var self = this;
	var query=self.req.query,setobj={};
	let col=decodeURI(self.params.name);
	if(isNaN(query["id"]*1)){setobj["_id"]=require('mongodb').ObjectId(query["id"]);}else{setobj["_id"]=query["id"]*1;}
	const mongo=MODULE('https_modules/HmongoDB');
	const con=await mongo.connfull(conURL);
	var model= await mongo.deleteONE(con.data,dbase,query["collection"],setobj);
	model.id=[query["id"]];
	model['data']=F.resource(model.status);
    self.status=200;
    self.json(model);
}
async function DELbulk(req,res){
	var self = this;
	var body=self.req.body;
	var model={},setobj={};
	//let limit=50,col=decodeURI(self.params.name);
	console.log(body);
	if(body["chk"].length>0){
    	const mongo=MODULE('https_modules/HmongoDB');
    	const con=await mongo.connfull(conURL);
     	model.id=[];
        var chk=body["chk"].length;
    	for(var i=0;i<chk;i++){
    	    model.id.push(body.chk[i]);
        	if(isNaN(body.chk[i]*1)){setobj["_id"]=require('mongodb').ObjectId(body.chk[i]);}else{setobj["_id"]=body.chk[i]*1;}
    	    body.chk[i]=setobj;
    	}
    	let query={};
    	 query["$or"]=body["chk"];
    	var x= await mongo.deleteMANY(con.data,dbase,body["collection"],query);
    	model.status= x.status;
	}else{model.status=700;}
    model['data']=F.resource(model.status);
	self.status=200;
    self.json(model);
}

async function view_UPDcollection(req,res){
	var self = this;
	let setobj={},col=decodeURI(self.params.name);
	const mongo=MODULE('https_modules/HmongoDB');
	console.log(decodeURI(self.params.name));
	const con=await mongo.connfull(conURL);
    	if(isNaN(self.params.id*1)){setobj["_id"]=require('mongodb').ObjectId(self.params.id);}else{setobj["_id"]=self.params.id*1;}
		var model=await mongo.findfull(con.data,dbase,col,setobj);
        model.collection=col;
	  self.layout('~../modules/https_modules/viewpartial/mongodb/mongopanel');
	self.view('~../modules/https_modules/viewpartial/mongodb/update',model);
}
async function post_UPDcollection(req,res){
	var self = this;
	var body=self.req.body;
	let filter={},col=decodeURI(self.params.name),id=decodeURI(self.params.id);
	const mongo=MODULE('https_modules/HmongoDB');
	const con=await mongo.connfull(conURL);
   	console.log(col);
   	console.log("dddddddddddddddddddddddddddddddddddddd");
   	console.log(body);
 	const valid=MODULE('https_modules/Hvalidation');
 	var setobj={},unsetobj=['yo'],itm,item,k;
    for(i=1;i<body.count;i+=5){
        itm=body["up"+i];
        if(itm==""){
            if(body["up"+(i+1)]!=body["up"+(i+2)]){unsetobj.push(body["up"+(i+1)]);}
            item=body["up"+(i+2)];
            setobj[item]=await valid.setVALUE(body["up"+(i+3)],body["up"+(i+4)]);
            //console.log(typeof setobj[item]);
        }else{
            unsetobj.push(itm);
        }
    }
	if(body.countlist.length>0){
        itm=(body.countlist.replace('-','')).split("-");
        item=itm.length;
        for(i=0;i<item;i++){
            k=itm[i]*1;
            setobj[body["up"+(k)]]=await valid.setVALUE(body["up"+(k+1)],body["up"+(k+2)]);
        }
	}
	if(isNaN(id*1)){filter["_id"]=require('mongodb').ObjectId(id);}else{filter["_id"]=id*1;}
	console.log(setobj);
	//var model=await mongo.upsertONEfull(con.data,dbase,col,filter,[{ $set: setobj },{ $unset:unsetobj}],{ upsert: true,returnNewDocument: false});    
	var model=await mongo.updateONEfree(con.data,dbase,col,filter,[{ $set: setobj },{ $unset:unsetobj}]);    
console.log(model);
	self.redirect('/mongo/collection/update/'+col+'/'+id);
}
async function view_INScollectionO(req,res){
	var self = this;
	var model={collection:decodeURI(self.params.name)};
	console.log(model.collection);
    self.layout('~../modules/https_modules/viewpartial/mongodb/mongopanel');
	self.view('~../modules/https_modules/viewpartial/mongodb/insertOne',model);
}
async function post_INScollectionO(req,res){
	var self = this,setobj={},body=self.req.body,k;
 	const valid=MODULE('https_modules/Hvalidation');
	let col=decodeURI(self.params.name);
    itm=(body.countlist.replace('-','')).split("-");
    item=itm.length;
    for(i=0;i<item;i++){
        k=itm[i]*1;
        setobj[body["up"+(k)]]=await valid.setVALUE(body["up"+(k+1)],body["up"+(k+2)]);
    }
	const mongo=MODULE('https_modules/HmongoDB');
	const con=await mongo.connfull(conURL);
	var model=await mongo.insertONE(con.data,dbase,col,setobj);    
	self.redirect('/mongo/collection/insertOne/'+col);
}
async function view_INScollectionM(req,res){
	var self = this;
	var model={collection:decodeURI(self.params.name)};
    self.layout('~../modules/https_modules/viewpartial/mongodb/mongopanel');
	self.view('~../modules/https_modules/viewpartial/mongodb/insertMany',model);
}
async function post_INScollectionM(req,res){
	var self = this,setobj=[],body=self.req.body,k;
 	const valid=MODULE('https_modules/Hvalidation');
	let col=decodeURI(self.params.name);
    itm=(body.countlist.replace('-','')).split("-");
    item=itm.length;
    for(i=0;i<item;i++){
        k=itm[i]*1;
        setobj.push(await valid.setVALUE(body["up"+(k)],"object"));
    }
	const mongo=MODULE('https_modules/HmongoDB');
	const con=await mongo.connfull(conURL);
	var model=await mongo.insertFULL(con.data,dbase,col,setobj);    
	self.redirect('/mongo/collection/insertMany/'+col);
}
async function view_INScollectionF(req,res){
	var self = this;
	var model={collection:decodeURI(self.params.name)};
    self.layout('~../modules/https_modules/viewpartial/mongodb/mongopanel');
	self.view('~../modules/https_modules/viewpartial/mongodb/insertFile',model);
}
async function post_INScollectionF(req,res){
	var self = this,setobj=[],body=self.req.body,k;
 	const valid=MODULE('https_modules/Hvalidation');
	let col=decodeURI(self.params.name);
    setobj=await valid.setVALUE(body.import.replace(/\\r\\n/g,""),"isarray");
	const mongo=MODULE('https_modules/HmongoDB');
	const con=await mongo.connfull(conURL);
	var model=await mongo.insertFULL(con.data,dbase,col,setobj);    
	self.redirect('/mongo/collection/insertFile/'+col);
    
}
