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

exports.install = function() {

	// Enable cors
	//CORS();

	// Define API routes
	//ROUTE('POST /api/newsletter/  *Newsletter --> @save');
	//ROUTE('POST /api/newsletter/  *Newsletter --> @save');
	//ROUTE('POST /api/contact/     *Contact --> @save');
	//ROUTE('POST/api/project/     *projects --> @save');
	//ROUTE('api/',index, ['get', 10000], 2048); // 2 MB
	// ROUTE('api/projects2/',edit_projects2, ['get', 10000], 2048); // 2 MB
	// ROUTE('api/projects23/',edit_projects2, ['get', 10000], 2048); // 2 MB
	// ROUTE('api/projects/insert2',edit_projects, ['post', 10000], 2048); // 2 MB

	ROUTE('login/selector',view_loginselector,['unauthorize']); // 2 MB
	ROUTE('login',view_login,['unauthorize']); // 2 MB	
	ROUTE('api/login',view_loginpost,['post','unauthorize'], 2048); // 2 MB  

	ROUTE('loginajax',view_loginAJAX,['ajax','get','unauthorize']); // 2 MB
	ROUTE('api/loginajax',view_loginAJAXpost,['post','upload','ajax','unauthorize']); // 2 MB

	ROUTE('api/logout',view_logout,['authorize']); // 2 MB  
	// ROUTE('api/panel',view_panel,['authorize','@admin','@administrator','@user','@customer']); // 2 MB



	ROUTE('/forget',view_forgetpass,['unauthorize']); // 2 MB
	ROUTE('/forget/num',forgetNum,['post','upload','ajax','unauthorize']); // 2 MB
	ROUTE('/forget/num/ok',forgetNumOk,['post','upload','ajax','unauthorize']); // 2 MB
	ROUTE('/forget/recovery',forgetrecovery,['post','upload','ajax','unauthorize']); // 2 MB
	ROUTE('/forget/mail',forgetMail,['post','upload','ajax','unauthorize']); // 2 MB
	ROUTE('/forget/mail/ok',forgetMailok,['post','upload','ajax','unauthorize']); // 2 MB
	ROUTE('/recoveryBYmail/{token}',forgetMailrecived,['get','unauthorize']); // 2 MB
	ROUTE('/changepassword',changepassword,['post','upload','ajax','authorize','@admin','@user','@customer']); // 2 MB
	ROUTE('/changepassword',vew_changepassword,['post','authorize']); // 2 MB
	ROUTE('/forgot',view_forgetacc,['unauthorize']); // 2 MB


    
    ROUTE('/login/github/', oauth_login, ['unauthorize']);
    ROUTE('/login/github/callback/', oauth_login_callback, ['unauthorize']);
    ROUTE('/login/facebook/', oauth_login, ['unauthorize']);
    ROUTE('/login/facebook/callback/', oauth_login_callback, ['unauthorize']);
    ROUTE('/login/dropbox/', oauth_login, ['unauthorize']);
    ROUTE('/login/dropbox/callback/', oauth_login_callback, ['unauthorize']);
    ROUTE('/login/linkedin/', oauth_login, ['unauthorize']);
    ROUTE('/login/linkedin/callback/', oauth_login_callback, ['unauthorize']);

    ROUTE('/login/google/', oauth_login, ['unauthorize']);
    ROUTE('/login/google/callback/', oauth_login_callback, ['unauthorize']);

    ROUTE('/login/yahoo/', oauth_login, ['unauthorize']);
    ROUTE('/login/yahoo/callback/', oauth_login_callback, ['unauthorize']);
    ROUTE('/login/live/', oauth_login, ['unauthorize']);
    ROUTE('/login/live/callback/', oauth_login_callback, ['unauthorize']);
    ROUTE('/login/instagram/', oauth_login, ['unauthorize']);
    ROUTE('/login/instagram/callback/', oauth_login_callback, ['unauthorize']);
    ROUTE('/login/msgraph/', oauth_login, ['unauthorize']);
    ROUTE('/login/msgraph/callback/', oauth_login_callback, ['unauthorize']);


}
async function login(sms="") {
	var k={};
	// fs=require(fs);
	// fs.exist()
	var name=PATH.root("modules/https_modules/viewpartial/loginfix.json");
	const fs=require('fs');
	var ok=await fs.existsSync(name);
	if(ok){
		k=await JSON.parse(fs.readFileSync(name));
		if(k["cover"]==""){k["cover"]=k["back"];}
	}else{
		k["page"]="loginDuo";
		k["back"]="none";
		k["cover"]="none";
		k["over"]="none";

	}
	k["sms"]=sms;
		var model=await VIEW("~partial/../../modules/https_modules/viewpartial/"+k.page,k);

//	var model=await VIEW("./modules/https_modules/viewpartial/"+k.page,k);
	return model;

}
async function view_login(req, res) {
	var self = this;
	var model=await login();
	self.layout('');
	self.view('login',model);
}


async function view_loginpost(req, res) {
	var self = this;
	var body=self.req.body;
	var id=self.params;
	await F.userlogin(self,dbase, body["user"],body["pass"],{username:0,password:0,idcode:0,phone:0,email:0,active:0});
	//controller.repository.login
	if(self.repository.login){
		var model=["gggg"];
	   //self.layout('layouts/admin');
	   self.redirect('/api')
    }else{
		var model=await login("نام کاربری یا کلمه عبور صحیح نمی باشد");
		self.layout('');
		self.view('/login',model);
	}
}


async function view_loginAJAX(req, res) {
	var self = this;
	self.status=200;
	var model=await VIEW("~partial/../../modules/https_modules/viewpartial/loginajax");
	var result={'status':200,'data':""};
	result.data=model;
	self.json(result);
}

async function view_loginAJAXpost(req, res) {
	var self = this;
	var body=self.req.body;
	var id=self.params;
	self.status=200;
	var result={'status':200,'data':""};
	await F.userlogin(self,dbase, body["username"],body["pass"],{username:0,password:0,idcode:0,phone:0,email:0,active:0});
	//controller.repository.login
	if(self.repository.login){
		result.data="کاربر گرامی خوش آمدید";
		result.status=200;
    }else{
		result.status=404;
		result.data="نام کاربری یا کلمه عبور صحیح نمی باشد";
	}
	self.json(result);
}

async function view_panel(req, res) {
	var self = this;
	// const x=MODULE('https_modules/Hfiles');
	// var name=PATH.public("images/logo.png");
	//await x.deletefile(name);
	// var user=await db_find_one("amlakbahar","user",{_id:1},{_id:1,name:1,fam:1,role:1})
	var user = self.user
	var model=[];
	var partial=require(PATH.root('/controllers/partial/panel'));
	if(user.role=="customer"){
		//console.log("USER ROLE CUSTOMER");
	}else{
		//console.log("USER ROLE NO CUSTOMER");
	}
			//  await F.userlogin(self, user[0]);
	
			//  ROUTE('api/login',view_login,['unauthorize']); // 2 MB
			//  ROUTE('api/panel',view_panel,['authorize','@admin','@admin','@user']); // 2 MB
		self.layout('layouts/admin');
	self.view('/admin/panel',model);
}


async function view_logout(req, res) {
	var self = this;
	var body=self.req.body;
	var id=self.params;
	await F.userlogoff(self);
	//controller.repository.login

		self.redirect('/login');
	
}




async function view_forgetacc(req, res) {
	var self = this;

	var user = self.user
	var model=await VIEW("~partial/../../modules/https_modules/viewpartial/forgot");
	self.layout('');
	self.view('login',model);
}

async function view_forgetpass(req, res) {
	var self = this;
	var user = self.user
	var model=await VIEW("~partial/../../modules/https_modules/viewpartial/forget");
	self.layout('');
	self.view('login',model);
}

async function forgetNum(req, res) {
	var self = this;
	var result={};
	const mongo=MODULE('https_modules/HmongoDB');
	const valid=mongo.ISvalidate;
	const con=await mongo.connfull(conURL);
	result["status"]=200;
	if(valid(self.req.body["user"])){
		if(con.status==200){
			var s=await mongo.join2merge(con.data,dbase,"user","_id","user-info","_id",{"username":self.req.body["user"]});// limitation =1 for test
			if(s.status==200 && s.data.length==1){
				//send sms to phone
				var text=s.data[0].phone;
				text="*"+text[1]+"* *"+text[4]+text[5]+" *"+text[7]+text[8]+"*";
				result["phone"]=text;
				result["name"]=self.req.body["user"];
			}else{
				result.status=300;
			}
		}else{
			result.status=500;
		}
	}else{
		result.status=700;
	}
	self.status=200;
	self.json(result)

}
async function forgetNumOk(req, res) {
	var self = this;
	var result={};
	const mongo=MODULE('https_modules/HmongoDB');
	const valid=mongo.ISvalidate;
	const con=await mongo.connfull(conURL);
	result["status"]=200;
	if(valid(self.req.body["user"]) && valid(self.req.body["ok"])){
		if(self.req.body["ok"]==1379){
			if(con.status==200){
				var s=await mongo.join2merge(con.data,dbase,"user","_id","user-info","_id",{"username":self.req.body["user"]});// limitation =1 for test
				if(s.status==200 && s.data.length==1){
					//make token
					var user={};
					user["code"]=s.data[0].id;
					var tokken=	await F.tokenMaker(user);
					s=await mongo.updateONEfull(con.data,dbase,"user",{_id:s.data[0]._id*1},{$set:{token:tokken}},{upsert: true,returnNewDocument: false});
					if(s.status==200){
						result["token"]=tokken;
						result["name"]=self.req.body["user"];
					}else{
						result.status=400;
					}

				// 	F.tokenExtracer=async function(token){
				//   return F.decrypt(token, SECRET);
				// }
				}else{
					result.status=300;
				}
			}else{
				result.status=500;
			}
		}else{
			result.status=400;
		}
	}else{
		result.status=700;
	}

	self.status=200;
	self.json(result)

}
async function forgetrecovery(req, res) {
	var self = this;
	var result={};
	const mongo=MODULE('https_modules/HmongoDB');
	const valid=mongo.ISvalidate;
	const con=await mongo.connfull(conURL);
	result["status"]=900;
	if(valid(self.req.body["user"]) && valid(self.req.body["token"]) && valid(self.req.body["pass"])){

		if(con.status==200){
			var x=await mongo.findfull(con.data,dbase,"user",{$and:[{"username":self.req.body["user"]},{token:self.req.body["token"]}]});
			if(x.status==200 && x.data.length==1){
				//send pass to sms
				var s=await mongo.updateONEfull(con.data,dbase,"user",{_id:x.data[0]._id*1},[{$set:{password:self.req.body["pass"]}},{$unset:"token"}],{upsert: false,returnNewDocument: false});
				if(s.status==200){
				}else{
					result.status=300;
				}
			}else{
				result.status=400;
			}
		}else{
			result.status=500;
		}
	}else{
		result.status=700;
	}

	self.status=200;
	self.json(result)
	
}

async function forgetMail(req, res){
	var self=this
	var result={};
	const mongo=MODULE('https_modules/HmongoDB');
	const valid=mongo.ISvalidate;
	const con=await mongo.connfull(conURL);
	result["status"]=200;
	if(valid(self.req.body["user"])){
		if(con.status==200){
			var s=await mongo.join2merge(con.data,dbase,"user","_id","user-info","_id",{"username":self.req.body["user"]});// limitation =1 for test
			if(s.status==200 && s.data.length==1){
				//send sms to phone
				let star="***************";
				var text=s.data[0].email;
				var z=text.indexOf("@");
				let k=Math.floor(z/5);
				text=star.substr(0,k)+text.substr(k,k)+star.substr(2*k,k)+text.substr(3*k,k)+star.substr(0,z-4*k)+text.substr(z);
				result["mail"]=text;
				result["name"]=self.req.body["user"];
			}else{
				result.status=300;
			}
		}else{
			result.status=500;
		}
	}else{
		result.status=700;
	}
	self.status=200;
	self.json(result)

}
async function forgetMailok(req, res) {
	var self = this;
	var result={};
	const mongo=MODULE('https_modules/HmongoDB');
	const valid=mongo.ISvalidate;
	const con=await mongo.connfull(conURL);
	result["status"]=200;
	if(valid(self.req.body["user"]) && valid(self.req.body["email"])){
			if(con.status==200){
				var s=await mongo.join2merge(con.data,dbase,"user","_id","user-info","_id",{$and:[{"username":self.req.body["user"]},{"mail":self.req.body["mail"]}]});// limitation =1 for test
				if(s.status==200 && s.data.length==1){
					//make token
					var user={};
					user["code"]=s.data[0]._id;
					user["email"]=s.data[0].email;
					var tokken=	await F.tokenMaker(user);
					s=await mongo.updateONEfull(con.data,dbase,"user",{_id:s.data[0]._id*1},{$set:{token:tokken}},{upsert: true,returnNewDocument: false});
					if(s.status==200){
						 result["token"]=tokken;
						// result["name"]=self.req.body["user"];
						//console.log(tokken);
					}else{
						result.status=400;
					}

				// 	F.tokenExtracer=async function(token){
				//   return F.decrypt(token, SECRET);
				// }
				}else{
					result.status=300;
				}
			}else{
				result.status=500;
			}
	}else{
		result.status=700;
	}

	self.status=200;
	self.json(result)

}
async function forgetMailrecived(req, res) {
	var self = this;
	//console.log("forgeeeeeeeeeeeeeeeeeMAILeeeeeeeeeeeeeeeeeeet");
	var user = self.user
	const mongo=MODULE('https_modules/HmongoDB');
	const valid=mongo.ISvalidate;
	var mod={"status":true,"data":""};
	if(valid(self.params["token"])){
		const con=await mongo.connfull(conURL);
		if(con.status==200){
			var tokken= await F.tokenExtracer(self.params["token"])
			var s=await mongo.join2merge(con.data,dbase,"user","_id","user-info","_id",{$and:[{"_id":tokken.code*1},{"email":tokken.email},{"token":self.params["token"]}]});// limitation =1 for test
			//console.log(s);
			//console.log(tokken);
			if(s.status==200 && s.data.length==1){
				//172800000
				if(((new Date().getTime()*1)-tokken.date*1)<172800000){
					mod.data=s.data[0];
				}else{
					mod={"status":false,"data":"100"};
				}
			}else{
				mod={"status":false,"data":"400"};
			}
		}else{
			mod={"status":false,"data":"500"};
		}
	}else{
		mod={"status":false,"data":"700"};
	}
	//console.log(mod);
	var model=await VIEW("~partial/../../modules/https_modules/viewpartial/emailrecovery",mod);
	self.layout('');
	self.view('login',model);
}

async function changepassword(req, res) {
	var self = this;
	var result={};
	const mongo=MODULE('https_modules/HmongoDB');
	const valid=mongo.ISvalidate;
	const con=await mongo.connfull(conURL);
	result["status"]=200;
	//console.log(self.req.body["renewpass"]);
	//console.log(self.req.body["oldpass"]);
	//console.log(self.req.body["newpass"]);
	if(valid(self.req.body["renewpass"]) && valid(self.req.body["oldpass"]) && valid(self.req.body["newpass"])){
	  if(self.req.body["renewpass"]==self.req.body["newpass"]){
		if(con.status==200){
			var x=await mongo.findfull(con.data,dbase,"user",{$and:[{"_id":self.user._id*1},{"password":self.req.body["oldpass"]}]});
			//console.log(x);
			if(x.status==200 && x.data.length==1){
				//send pass to sms
				var s=await mongo.updateONE(con.data,dbase,"user",{_id:self.user._id*1},{password:self.req.body["newpass"]});
				//console.log(s);
				if(s.status==200){
				}else{
					result.status=300;
				}
			}else{
				result.status=400;
			}
		}else{
			result.status=300;
		}
	  }else{
		result.status=720;
	  }
	}else{
		result.status=700;
	}

	self.status=200;
	self.json(result)
	
}
async function vew_changepassword(req, res) {
	var self = this;
	var result={};
	const mongo=MODULE('https_modules/HmongoDB');
	const valid=mongo.ISvalidate;
	const con=await mongo.connfull(conURL);
	result["status"]=200;
	//console.log(self.req.body["renewpass"]);
	//console.log(self.req.body["oldpass"]);
	//console.log(self.req.body["newpass"]);
	//console.log(self.req.body["errpage"]);
	//console.log(self.req.body["okpage"]);
	//console.log(self.req.body["layoutokpage"]);
	//console.log(self.req.body["layouterrpage"]);
	if(valid(self.req.body["renewpass"]) && valid(self.req.body["oldpass"]) && valid(self.req.body["errpage"]) && valid(self.req.body["okpage"]) && valid(self.req.body["newpass"])){
	  if(self.req.body["renewpass"]==self.req.body["newpass"]){
		if(con.status==200){
			var x=await mongo.findfull(con.data,dbase,"user",{$and:[{"_id":self.user._id*1},{"password":self.req.body["oldpass"]}]});
			//console.log(x);
			if(x.status==200 && x.data.length==1){
				//send pass to sms
				var s=await mongo.updateONE(con.data,dbase,"user",{_id:self.user._id*1},{password:self.req.body["pass"]});
				//console.log(s);
				if(s.status==200){
					self.layout(self.req.body["layoutokpage"]);
					self.redirect(self.req.body["okpage"]);
				}else{
					result.status=300;
				}
			}else{
				result.status=400;
			}
		}else{
			result.status=300;
		}
	  }else{
		result.status=720;
	  }
	}else{
		result.status=700;
	}
	self.layout(self.req.body["layouterrpage"]);

	if(valid(self.req.body["errpage"])){self.redirect(self.req.body["errpage"]+"/"+result.status);}
	self.redirect("404");
}







// Controller action
function oauth_login() {
	//console.log("ddddddddddddddddddddddd");
    var self = this;
    var type = self.req.path[1];
	var oauth2 = {google:{key:"",secret:""},yahoo:{key:"",secret:""},linkedin:{key:"",secret:""},github:{key:"",secret:""}};
    // config:
    oauth2.google.key = "682925111090-sd8rgol45tc3sham54ngiocbdvpit4mq.apps.googleusercontent.com";
   oauth2.google.secret ="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";
    oauth2.github.key ="Iv1.2778a05f90de0c69";
    oauth2.yahoo.key ="dj0yJmk9ck1kTnp5c0Z6azU3JmQ9WVdrOVNsZExUMnhLYVZrbWNHbzlNQT09JnM9Y29uc3VtZXJzZWNyZXQmc3Y9MCZ4PWUx";
    oauth2.yahoo.secret ="fe89d0e6b9bc33677decb9670f040ee36c1e2f21";
    oauth2.linkedin.key ="ljz0O55ebvX2LSODrH8xDqYp";
    oauth2.linkedin.secret ="nnekJ7nW2e89Qg7cbINmCqPXsa8dvfx14E9KvhxwnOZatpve";
    // oauth2.google.key ="";
    // oauth2.google.secret ="";
    // oauth2.github.key ="";
    // oauth2.github.secret ="";
    // ...
	//console.log("llllllllllllllllllllllllllll");
	//console.log(self.host('/login/' + type + '/callback/'));
	//console.log(oauth2[type].key);
    MODULE('oauth2').redirect(type, oauth2[type].key, self.host('/login/' + type + '/callback/'), self);
    // MODULE('oauth2').redirect(type, CONFIG('oauth2.' + type + '.key'), self.host('/login/' + type + '/callback/'), self);
// //console.log(oauth2.google.key);
	// return 'https://accounts.google.com/o/oauth2/v2/auth?scope=https://www.googleapis.com/auth/drive.metadata.readonly&access_type=offline&include_granted_scopes=true&response_type=code&state=state_parameter_passthrough_value&redirect_uri="/login/google/callback/"&client_id=oauth2.google.key';

    // OpenPlatform:
    // MODULE('oauth2').redirect(type, CONFIG('oauth2.' + type + '.key'), self.host('/login/' + type + '/callback/'), self, OPENPLATFORM_URL_ADDRESS);
}

// Controller action
function oauth_login_callback() {
    var self = this;
    var type = self.req.path[1];
    var url = self.host('/login/' + type + '/callback/');

	var oauth2 = {google:{key:"",secret:""},yahoo:{key:"",secret:""},linkedin:{key:"",secret:""},github:{key:"",secret:""}};
    // config:
    oauth2.google.key = "682925111090-sd8rgol45tc3sham54ngiocbdvpit4mq.apps.googleusercontent.com";
   oauth2.google.secret ="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";
    oauth2.github.key ="Iv1.2778a05f90de0c69";
     oauth2.github.secret ="9bf4b3909b2246ecd60c83569e8020633aff0989";

    oauth2.yahoo.key ="dj0yJmk9ck1kTnp5c0Z6azU3JmQ9WVdrOVNsZExUMnhLYVZrbWNHbzlNQT09JnM9Y29uc3VtZXJzZWNyZXQmc3Y9MCZ4PWUx";
    oauth2.yahoo.secret ="fe89d0e6b9bc33677decb9670f040ee36c1e2f21";
    oauth2.linkedin.key ="ljz0O55ebvX2LSODrH8xDqYp";
    oauth2.linkedin.secret ="nnekJ7nW2e89Qg7cbINmCqPXsa8dvfx14E9KvhxwnOZatpve";
    // oauth2.google.key ="";
    // oauth2.google.secret ="";
    // oauth2.github.key ="";
    // oauth2.github.secret ="";
    // ...

    MODULE('oauth2').callback(type,  oauth2[type].key,  oauth2[type].secret, url, self, function(err, profile, access_token) {
        //console.log("err------->");
        //console.log(err);
        //console.log("profile------->");
        //console.log(profile);
		// //console.log(profile.parseJSON().family_name);
		// //console.log(profile.parseJSON().name);
		// //console.log(profile.parseJSON().name);
		// //console.log(profile.parseJSON().name);




		// {
		// 	"family_name": "Belinsky", 
		// 	"name": "Teodor Belinsky", 
		// 	"picture": "https://lh3.googleusercontent.com/a/AATXAJztQZu-LKeCDtueb_IMrI7qZj8E01OHUQdbRfv-=s96-c", 
		// 	"locale": "cs", 
		// 	"email": "teodorbelinsky@gmail.com", 
		// 	"given_name": "Teodor", 
		// 	"id": "101452364612294717311", 
		// 	"verified_email": true
		//   }


        self.json(profile);
    });
    // MODULE('oauth2').callback(type, CONFIG('oauth2.' + type + '.key'), CONFIG('oauth2.' + type + '.secret'), url, self, function(err, profile, access_token) {
    //     //console.log(profile);
    //     self.json(SUCCESS(true));
    // });

    // OpenPlatform:
    // MODULE('oauth2').callback(type, CONFIG('oauth2.' + type + '.key'), CONFIG('oauth2.' + type + '.secret'), url, self, function(err, profile, access_token) {
    //     //console.log(profile);
    //     self.json(SUCCESS(true));
    // }, OPENPLATFORM_URL_ADDRESS);
}

async function view_loginselector(req,res){

	// fs=require(fs);
	// fs.exist()
	var name=PATH.root("modules/https_modules/viewpartial/image.json");
	const fs=require('fs');
	var ok=await fs.existsSync(name);
	if(ok){
		var k=await JSON.parse(fs.readFileSync(name));
		//console.log(k);

	}
	




	model=VIEW("~partial/../../modules/https_modules/viewpartial/loginDuo",page);


}