const { data } = require("jquery");


const conURLA=CONFIG("conURLA");
var ObjectId = require('mongodb').ObjectID;
//-------------------------------------------------------ok
exports.LSTusersFilter = async function(controller,dbase){
    const mongo=MODULE('https_modules/HmongoDB');
    var s={};
    let body=controller.req.body;
    query={};
    if(body['query']!="phone"){
       query[body['query']]=body['text']; 
    }else{
        query["phone.v"]=body['text'];
    }
    
  
    // if(controller.user._id>1){
        
    //     if(controller.user._id>2){
    //         query['$and']=[{_id:{$ne:1}},{_id:{$ne:2}}];
    //     }else{
    //         query['_id']={$ne:1};
    //     }
    // }
    
    
   console.log(query);
    var call1,call2;
    if(body['query']=="username"){
        call1="user";
        call2="user-info";
    }else{
        call1="user-info";
        call2="user";
    }
    
    const con=await mongo.connfull(conURLA);
    if(con.status==200){
        s=await mongo.join2merge(con.data,dbase,call1,"_id",call2,"_id",query);
        console.log(s);
        mongo.disconn(con.data);
        return s;
    }else{
        s["status"]=500;
        return s;
    }
}

// exports.INSuser1 = async function(controller,dbase,username,password,active,role){
//     let self=controller;
// 	let result={};
// let body=controller.req.body;
// const mongo=MODULE('https_modules/HmongoDB');
// const valid=mongo.ISvalidate;
// //chek sms code
// 	if(valid(body["name"]) && !isNaN(body["phone"]) && valid(body["phone"]) && ((!isNaN(body["idcode"]) && body["idcode"].length==10 && valid(body["idcode"]))||controller.user.role=="admin") && valid(body["fam"]) && valid(password) && valid(username)){
// 		const con=await mongo.connfull(conURL);
// 		result["status"]=200;
// 		if(con.status==200){
// 			var query={$or:[{"phone":body['phone']},{$and:[{"idcode":body["idcode"]},{"idcode":{$ne:""}}]},{"username":username}]}
// 			var s=await mongo.join2merge(con.data,dbase,"user","_id","user-info","_id",query);
// 			if(s.data.length==0){
// 				//sabt shavad ligin shavad
// 				var res=await mongo.idmaker(con.data,dbase,"collectionsID",270,"user");
// 				if(res.status){
// 					var ins_obj ={ _id:res.idnum*1,	idcode:body["idcode"] , name:body["name"] , fam:body["fam"],
// 								  phone:body["phone"]  ,email:body["email"], status:body["status"],telegram:body['telegram'],whatsapp:body['whatsapp'],instagram:body['instagram'] };
// 					var res2=await mongo.insertONE(con.data,dbase,"user-info",ins_obj);
// 					if(res2.status){
// 						var ins_obj ={ _id:res.idnum*1,username:username,password:password , active:(valid(active))?true:false ,role:role};
// 						var res3=await mongo.insertONE(con.data,dbase,"user",ins_obj);
// 						if(res2.status){
// 							result["status"]=200;
// 							result['data']={_id:res.idnum*1, name:body["name"] , fam:body["fam"], status:body["status"] ,role:role};
// 						}else{
// 							result["status"]=211;
// 						}
// 					}else{
// 						result["status"]=210;
// 					}
// 				}else{
// 					result["status"]=506;
// 				}
// 			}else{
// 				if(s.data[0].username==username){
// 					result["status"]=204;
//                     result["sms"]="نام کاربری قبلا انتخاب شده است";
// 				}
//                 else if(s.data.length>1){
//                     result["status"]=203;
//                     result["sms"]="کد ملی یا شماره تلفن برای شخص دیگری قبلا ثبت گردیده است<br/>می توانید با واحد پشتیبانی تماس گرفته و این موضوع را پیگیری کنید";
//                 }else{
//                     var query={$and:[{"name":body["name"]},{"fam":body["fam"]},{"phone":body["phone"]},{"idcode":body["idcode"]}]};
//                     var s=await mongo.findfull(con.data,dbase,"user-info",query);
//                     if(s.status==200){
//                         result["status"]=202;
//                     	result["sms"]="کاربر دیگری با همین مشخصات از پیش ثبتنام کرده است";
//                     }else{
//                         result["status"]=201;
//                     	result["sms"]="کد ملی یا شماره تلفن برای شخص دیگری قبلا ثبت گردیده است<br/>می توانید با واحد پشتیبانی تماس گرفته و این موضوع را پیگیری کنید";
//                     }
//                 }
// 			}
// 		}else{
// 			result["status"]=500;
// 		}
// 		mongo.disconn(con.data);
// 	}else{
// 		result["status"]=700;
// 	}

// return result;
// }
//-------------------------------------------------------ok
exports.INSuser = async function(self,dbase,body){
	let result={};
    const mongo=MODULE('https_modules/HmongoDB');
	const con=await mongo.connfull(conURLA);
		result["status"]=203;
		if(con.status==200){
            body["password"]=body["password"].replace(/\s/g, '');
            body['username']=body['username'].replace(/\s/g, '');
			if(valid(body["username"]) && valid(body["password"]) && body["password"].length>5 && body["username"].length>3){
			    var query={"username":body["username"]};
    			var s=await mongo.findfull(con.data,dbase,"user",query);
    			console.log(s);
    			if(s.data.length==0){
                            if((body["role"]=="administrator") && (self.user.role!="administrator")){
                                result["status"]=300;
                                mongo.disconn(con.data);
                                return result;
                            }
                            
    						var ins_obj ={username:body["username"],password:body["password"]+"",active:(valid(body["active"]))?true:false,role:body["role"]};
    						(body['ulist']!="")? ins_obj.unit=body['ulist'].split(","):"";
    						var res3=await mongo.insertONE(con.data,dbase,"user",ins_obj);

    						console.log(res3);
    						if(res3.status==200){
    							result["status"]=200;
    							result['data']=res3.data.insertedId;
    						}else{
    							result["status"]=301;
    						}
    			}else{
    			    if(s.data.length>1){
                        result["status"]=706;
    			    }else{
    	    		
                        result["status"]=705;
                    }
    			}
			}else{
			    result["status"]=700;
			}
		}else{
			result["status"]=500;
		}
		mongo.disconn(con.data);

return result;
}


exports.UPDuser = async function(self,dbase,body){
	let result={};
    const mongo=MODULE('https_modules/HmongoDB');
	const con=await mongo.connfull(conURLA);
		result["status"]=203;
		if(con.status==200){
		        var id=new ObjectId(body['userID']);
		        console.log(valid(body["username"]));
		        console.log(valid(id));
		        body['username']=body['username'].replace(/\s/g, '');
                if(valid(body["username"]) && valid(id) && body['username'].length>3){
                    var query={"username":body["username"]};
        			var s=await mongo.findfull(con.data,dbase,"user",query);
                    
                    if((s.data.length==0) || ((s.data.length>0) && (s.data[0]._id==body["userID"]))){
                        if((s.data[0].role=="administrator" || s.data[0].role=="admin") && (self.user.role!="administrator") && (s.data[0]._id!=self.user._id)){
                            result["status"]=302;
                            mongo.disconn(con.data);
                            return result;
                        }
                        body["password"]=body["password"].replace(/\s/g, '');
                        if(valid(body["password"]) && valid(body["role"]) && body["password"].length>5){
                            
                            if((body["role"]=="administrator") && (self.user.role!="administrator")){
                                result["status"]=302;
                                mongo.disconn(con.data);
                                return result;
                            }
                            var unit=[];
                            unit=(body['ulist']!="")? body['ulist'].split(","):[];
                			var upd_obj ={username:body["username"],password:body["password"]+"",active:(valid(body["active"]))?true:false,role:body["role"],unit:unit};
                			var res3=await mongo.updateONE(con.data,dbase,"user",{_id:id},upd_obj);
                			console.log(res3);
                			if(res3.status==200){
                				result["status"]=200;
                			}else{
                				result["status"]=301;
                			}
                        }else{
                            result["status"]=700;
                        }
        		    }else{
        		        result["status"]=703
        		    }
                }else{
                    result["status"]=700;
                }
		}else{
			result["status"]=500;
		}
		mongo.disconn(con.data);

return result;
}



exports.INSuserinfo = async function(dbase,body,id){
	let result={};
    const mongo=MODULE('https_modules/HmongoDB');
	const con=await mongo.connfull(conURLA);
		result["status"]=203;
		if(con.status==200){
			
			var ins_obj ={_id:id};
			(valid(body["name"]))?ins_obj.name=body["name"].trim():"";
			(valid(body["fam"]))?ins_obj.fam=body["fam"].trim():"";
			(valid(body["idcode"]))?ins_obj.idcode=body["idcode"].trim():"";
			(valid(body["email"]))?ins_obj.email=body["email"].trim():"";
			if(body["plist"]!=""){
			    var phone=[];
			    var plist=body["plist"].split(",");
			    console.log(plist);
			    for(var i=0;i<plist.length;i++){
			        var obj={k:"",v:""};
			        obj.k=body["p"+plist[i]];
			        obj.v=body["p"+(Number(plist[i])+1)];
			        phone.push(obj);
			    }
			    console.log(phone);
			    ins_obj.phone=phone;
			}
			
			console.log(ins_obj);
			
			var res3=await mongo.insertONE(con.data,dbase,"user-info",ins_obj);
			console.log(res3);
			if(res3.status==200){
				result["status"]=200;
				result['data']=id;
			}else{
				result["status"]=301;
			}

		}else{
			result["status"]=500;
		}
		mongo.disconn(con.data);

return result;
}




exports.UPDuserinfo = async function(dbase,body,id){
	let result={};
    const mongo=MODULE('https_modules/HmongoDB');
	const con=await mongo.connfull(conURLA);
		result["status"]=203;
		if(con.status==200){
			var upd_obj ={name:(valid(body["name"]))?body["name"].trim():"",fam:(valid(body["fam"]))?body["fam"].trim():"",idcode:(valid(body["idcode"]))?body["idcode"].trim():"",email:(valid(body["email"]))?body["email"].trim():""};
			if(body["plist"]!=""){
			    var phone=[];
			    var plist=body["plist"].split(",");
			    for(var i=0;i<plist.length;i++){
			        var obj={k:"",v:""};
			        obj.k=body["p"+plist[i]];
			        obj.v=body["p"+(Number(plist[i])+1)];
			        phone.push(obj);
			    }
			    console.log(phone);
			}
			upd_obj.phone=phone;
			console.log(upd_obj);
			
			var res3=await mongo.updateONE(con.data,dbase,"user-info",{_id:id},upd_obj);
			console.log(res3);
			if(res3.status==200){
				result["status"]=200;
			}else{
				result["status"]=301;
			}

		}else{
			result["status"]=500;
		}
		mongo.disconn(con.data);

return result;
}





exports.INSuseraddress = async function(dbase,body,id){
	let result={};
    const mongo=MODULE('https_modules/HmongoDB');
	const con=await mongo.connfull(conURLA);
		result["status"]=203;
		if(con.status==200){
			
	
			if(valid(body["postcode"]) && valid(body["address"]) && valid(body["city"]) && valid(body["province"])){
    			
                var ins_obj ={_idu:id,_idp:body["province"]*1,_idc:body["city"]*1,postcode:body["postcode"]*1,address:body["address"]};
    

    			var res3=await mongo.insertONE(con.data,dbase,"user-address",ins_obj);

    			if(res3.status==200){
    				result["status"]=200;
    				ins_obj._id=res3.data.insertedId;
    				result['data']=ins_obj;
    			}else{
    				result["status"]=301;
    			}
			}else{
			    result["status"]=700;
			}

		}else{
			result["status"]=500;
		}
		mongo.disconn(con.data);

    return result;
}



exports.UPDuseraddress = async function(dbase,body,uid){
	let result={};
    const mongo=MODULE('https_modules/HmongoDB');
	const con=await mongo.connfull(conURLA);
		result["status"]=203;
		if(con.status==200){
			
	
			if( valid(body["addressid"]) && valid(body["postcode"]) && valid(body["address"]) && valid(body["city"]) && valid(body["province"])){
			    
    			var id=new ObjectId(body["addressid"]);
    			
                var upd_obj ={_idp:body["province"]*1,_idc:body["city"]*1,postcode:body["postcode"]*1,address:body["address"]};

    			var res3=await mongo.updateONE(con.data,dbase,"user-address",{$and:[{_id:id},{_idu:uid}]},upd_obj);

    			if(res3.status==200){
    				result["status"]=200;

    			}else{
    				result["status"]=301;
    			}
			}else{
			    result["status"]=700;
			}

		}else{
			result["status"]=500;
		}
		mongo.disconn(con.data);

    return result;
}


exports.DELuseraddress = async function(dbase,id,uid){
	let result={};
    const mongo=MODULE('https_modules/HmongoDB');
	const con=await mongo.connfull(conURLA);
		result["status"]=203;
		if(con.status==200){
			
			if(valid(id)){

    			var res3=await mongo.deleteONE(con.data,dbase,"user-address",{$and:[{_id:id},{_idu:uid}]});

    			if(res3.status==200){
    				result["status"]=200;
    				result["id"]=id;

    			}else{
    				result["status"]=301;
    			}
			}else{
			    result["status"]=700;
			}

		}else{
			result["status"]=500;
		}
		mongo.disconn(con.data);

    return result;
}







    exports.UPDusermedia = async function(controller,dbase,id){
        let result={};
        const mongo=MODULE('https_modules/HmongoDB');
        const con=await mongo.connfull(conURLA);
            result["status"]=203;
            if(con.status==200){    
                let query=controller.req.query;
                query["obj"]=decodeURI(query["obj"]);
                query["obj"]=JSON.parse(query["obj"]);
                var obj=[];
                for(var i=0;i<query["obj"].length;i++){
                    if(valid(query["obj"][i].icon)&&valid(query["obj"][i].link)&&valid(query["obj"][i].title)){
                        obj.push({icon:query["obj"][i].icon,title:query["obj"][i].title,link:query["obj"][i].link});
                    }else{
                        result["status"]=700;
                        mongo.disconn(con.data);
                        return result;
                    }
                }
                var res3=await mongo.upsertONEfull(con.data,dbase,"user-media",{_id:id},[{ $set: {media:obj} },{ $unset:['yo']}],{ upsert: true,returnNewDocument: false});    
                if(res3.status==200){
                    result["status"]=200;
                }else{
                    result["status"]=301;
                }
    
            }else{
                result["status"]=500;
            }
            mongo.disconn(con.data);
    
    return result;
    }
    
    
//-------------------------------------------------------ok
exports.INSuserpic = async function(controller,id){
    "use strict";
    let self=controller;
	let result={};
    
    let file = self.files[0];
    console.log(file);
    const mongo=MODULE('https_modules/HmongoDB');
    const valid=mongo.ISvalidate;
    //chek sms code
    
	if(valid(id)){
        if(file!=undefined){
            if(self.files.length>0){
                'use strict';
                console.log("heeeeeyyyyyyyyy");
                const image=MODULE('https_modules/Himages');
                var filename = PATH.public('images/users/user'+id+"_1.jpg");
                console.log(filename);
                var xxx=await image.Hfiles.copyTO(file,filename); 
                console.log(xxx);
                if(xxx.status==200){
                    result = await image.load_image(filename);
                    console.log(result);
                    result["id"]=id;
                    result["num"]=1;  
                }else{
                    result.status=314;
                }
            }else{
                result.status=711;
            }
        }else{
            result.status=710;
        }
	}else{
		result["status"]=700;
	}
return result;
}
//-------------------------------------------------------ok
exports.DELuserPic = async function(controller,dbase,id){
    "use strict";
	let result={};
    const files=MODULE('https_modules/Hfiles');
    var name="user"+id+'_1.jpg';
    let cc=await files.CHKdeletefile(PATH.public('images/users/'+name));
    result["status"]=200;
    // deleting file has not been deployed yet
return result;
}
//-------------------------------------------------------ok

//-------------------------------------------------------ok
exports.UPDuserPASS = async function(controller,dbase,id){
    const mongo=MODULE('https_modules/HmongoDB');
    var model={};
    console.log("888888888");
    model["status"]=205;
    let body=controller.req.body;
    //if((id==1) && ((controller.user._id*1)!=1)){model["status"]=413;}else{
        const con=await mongo.connfull(conURLA);
        if(con.status==200){

            var s=await mongo.updateONE(con.data,dbase,"user",{_id:id},{password:body['newpass']});
            
            model["data"]=s.data;
            mongo.disconn(con.data);
        }else{
            model["status"]=500; 
        }
    //}
    return model;
}


exports.UPDcustomerPASS = async function(controller,dbase,id){
    const mongo=MODULE('https_modules/HmongoDB');
    var model={};
    console.log("888888888");
    model["status"]=205;
    let body=controller.req.body;
    if((id==1) && ((controller.user._id*1)!=1)){model["status"]=413;}else{
        const con=await mongo.connfull(conURLA);
        
        if(con.status==200){
            var s=await mongo.findfull(con.data,dbase,"user",{_id:id});
            if(s.status==200){
                console.log(s);
                if(s.data[0].password==body["oldpass"]){
                    s=await mongo.updateONE(con.data,dbase,"user",{_id:id},{password:body['newpass']});
                    model["data"]=s.data;
                }else{
                    model["status"]=712; 
                }
            }else{
                model["status"]=400; 
                
            }
            
            mongo.disconn(con.data);
        }else{
            model["status"]=500; 
        }
    }
    return model;
}

//-------------------------------------------------------ok
exports.DELuser = async function(controller,dbase){
    //let self=controller;
	let result={};
    let query=controller.req.query;
    const mongo=MODULE('https_modules/HmongoDB');
    const valid=mongo.ISvalidate;
    //chek sms code
    var id=new ObjectId(query['id']);
    if((query['id']==controller.user._id) || (query["id"])==1){ //check admin 
        result['status']=103;
    }else{
	if(valid(query["id"])){
        const con=await mongo.connfull(conURLA);
        result["status"]=206;
        if(con.status==200){
            //var s=await mongo.findfull(con.data,dbase,'melk',{$or:[{_userid:query["id"]*1},{_registeraridid:query["id"]*1},{_confirmid:query["id"]*1}]},{_id:1});
            var s={status:404,data:[]};
            if((s.status==200) || (s.status==404 && s.data.length==0)){
                if(s.data.length>0){
                    result["status"]=309;
                    result['id']=query["id"];
                }else{
                    var userInfoDel=await mongo.deleteONE(con.data,dbase,'user-info',{_id:id});
                    if(userInfoDel.status==200){
                        var userAddressDel=await mongo.deleteMANY(con.data,dbase,'user-address',{_idu:id});
                        if(userAddressDel.status==200){
                            var userDel=await mongo.deleteONE(con.data,dbase,'user',{_id:id});
                            if(userDel.status==200){
                                result['id']=query["id"];
                            }else{
                                //مشکل دیتابیس
                                result["status"]=305;
                            }
                        }else{
                            result["status"]=305;
                        }
                    }else{
                         //مشکل دیتابیس
                         result["status"]=304;
                    }
                }
            }else{
                //مشکل دیتابیس 
                result["status"]=500;
            }
            
            mongo.disconn(con.data);
        }else{
            result["status"]=500;
        }
	}else{
		result["status"]=700;
	}
}
return result;
}
//-------------------------------------------------------ok
exports.DELuser_force = async function(controller,dbase){
    //let self=controller;
	let result={};
    let query=controller.req.query;
    var id=new ObjectId(query['id']);
    const image=MODULE('https_modules/Hfiles');
    const mongo=MODULE('https_modules/HmongoDB');
    const valid=mongo.ISvalidate;
//chek sms code
if((query["id"]==controller.user._id)|| query["id"]==1){  //check admin 
    result['status']=103;
}else{
	if(valid(query["id"])){
        const con=await mongo.connfull(conURLA);
        result["status"]=200;
        if(con.status==200){
                    // if there is another collections that has data for the user , it might be deleted here 
                    
                    
                    var userAddressDel= await mongo.deleteMANY(con.data,dbase,'user-address',{_idu:id});
                    if(userAddressDel.status==200){
                        var userInfoDel=await mongo.deleteONE(con.data,dbase,'user-info',{_id:id});
                        if(userInfoDel.status==200){
                            var userDel=await mongo.deleteONE(con.data,dbase,'user',{_id:id});
                            if(userDel.status==200){
                                result["status"]=200;
                                result['id']=query["id"];
                            }else{
                                //مشکل دیتابیس
                                result["status"]=305;
                            }
                        }else{
                             //مشکل دیتابیس
                             result["status"]=305;
                        }
                    }else{
                        //مشکل دیتابیس 
                        result["status"]=304;
                    }
            
            mongo.disconn(con.data);
        }else{
            result["status"]=500;
        }
	}else{
		result["status"]=700;
	}
}
return result;
}



exports.DELmultiuser = async function(controller,dbase){
    //let self=controller;
	let result={};
    let body=controller.req.body;
    // var idlist=new ObjectId(query['id']);
    
    var idlist=body["users"].split(",");
    const image=MODULE('https_modules/Hfiles');
    const mongo=MODULE('https_modules/HmongoDB');
    const valid=mongo.ISvalidate;
    console.log(idlist);
    console.log("666666666666666666666666666666666666666666666666666666666666");
//chek sms code
// result["status"]=700;
// return result;
if((idlist.indexOf(controller.user._id)>-1)|| (idlist.indexOf(1)>-1)){  //check admin 
    result['status']=103;
}else{
	if(valid(idlist)){

        const con=await mongo.connfull(conURLA);
        result["status"]=200;
        if(con.status==200){
            
                    // if there is another collections that has data for the user , it might be deleted here 
                    for(var i=0;i<idlist.length;i++){
                        idlist[i]=new ObjectId(idlist[i]);
                    }
                    console.log(idlist);
                    var userAddressDel= await mongo.deleteMANY(con.data,dbase,'user-address',{_idu:{$in:idlist}});
                    if(userAddressDel.status==200){
                        var userInfoDel=await mongo.deleteMANY(con.data,dbase,'user-info',{_id:{$in:idlist}});
                        if(userInfoDel.status==200){
                            var userDel=await mongo.deleteMANY(con.data,dbase,'user',{_id:{$in:idlist}});
                            if(userDel.status==200){
                                result["status"]=200;
                                
                            }else{
                                //مشکل دیتابیس
                                result["status"]=305;
                            }
                        }else{
                             //مشکل دیتابیس
                             result["status"]=305;
                        }
                    }else{
                        //مشکل دیتابیس 
                        result["status"]=304;
                    }
            
            mongo.disconn(con.data);
        }else{
            result["status"]=500;
        }
	}else{
		result["status"]=700;
	}
}
return result;
}



