"use strict";
var pwa = pwa || {};
/*
Manage user authentification and registration
________________________
pwa.auth.route()
  manage from state.json route if authenticated or not
  redirect public page or app page
________________________
pwa.auth.screenlogin()
  show login modal
________________________
pwa.auth.getlinkwithoutpsw()
    special get with token and uuid workeable for 24h this link is une onetime
_________________________
pwa.auth.isAuthenticate()
  test if token is still ok or not return false/true
_________________________
pwa.auth.authentification({LOGIN,PASSWORD})
  if ok => load pwa.state.data.app .headers .userlogin
_________________________
pwa.auth.login()
  Manage login modal to get login psw value and submit it to pwa.auth.authentification()
_________________________
pwa.auth.logout()
  Remove localstorage and reload
_________________________
pwa.auth.register()
   @TODO
__________________________
pwa.auth.forgetpsw()
  Request to send an email with a unique get link to access from this link to the app

*/
/*MODULEJS*/
//--##
pwa.auth = {};
// Refresh browser state if exist else get pwa.state defaults
//pwa.state.ready( pwa.auth.check );

pwa.auth.check = () => {
	if( pwa.state.data.login.isAuthenticated ) {
		if( !pwa.auth.isAuthenticate() ) {
			// Then reinit local storage and refresh page
			pwa.state.data.login.isAuthenticated = false;
			pwa.state.save();
			//alert( 'reload page cause no more auth' )
			window.location.reload();
		};
	}
};
pwa.auth.route = ( destination ) => {
	logger.info( 'auth.route to', destination );
	//if check Authenticated && exist #signin button[data-routeto] then redirect browser to button[data-routeto]
	//else manage component action auth
	if( pwa.state && pwa.state.data && pwa.state.data.login && pwa.state.data.login.isAuthenticated ) {
		if( destination )
			window.location.pathname = `${pwa.state.data.ctx.urlbase}/${destination}`;
	} else {
    [ "#signin", "#resetpsw", "#register" ].forEach( e => {
			if( e == destination ) {
				document.querySelector( e )
					.classList.remove( 'd-none' );
			} else {
				document.querySelector( e )
					.classList.add( 'd-none' );
			}
		} )
	}
}
pwa.auth.isAuthenticate = async function () {
	// in any request, if middleware isAuthenticated return false
	// then headers Xuuid is set to 1
	// then try pwa.auth.isAuthenticate if rememberMe auto reconnect
	// if jwt is ok then return true in other case => false
	// this is the first test then depending of action see ACCESSRIGHTS of user
	logger.info( 'lance isauth', {
		headers: pwa.state.data.headers.xpaganid
	} )
	//alert( 'uuid ' + pwa.state.data.headers.xpaganid )
	logger.info( `https://${pwa.state.data.ctx.urlbackoffice}/users/isauth`, {
		headers: pwa.state.data.headers
	} )
	try {
		const repisauth = await axios.get( `https://${pwa.state.data.ctx.urlbackoffice}/users/isauth`, {
			headers: pwa.state.data.headers
		} )
		logger.info( repisauth )
		logger.info( 'isAauthenticate: yes' )
		return true;
	} catch ( err ) {
		if( err.response ) { logger.info( "response err ", err.response.data ) }
		if( err.request ) { logger.info( "request err", err.request ) }
		logger.info( 'isAuthenticate: no' )
		pwa.state.data.headers.xpaganid = "1";
		if( pwa.state.data.login.rememberMe.login ) {
			if( await pwa.auth.authentification( pwa.state.data.login.rememberMe ) ) {
				return await pwa.auth.isAuthenticate();
			};
		}
		return false;
	}
};
pwa.auth.authentification = async function ( data ) {
	// Core client function to chech auth from login & psw
	// In case of 403 error lauch pwa.authentification(pwa.app.rememberMe)
	// in case of sucess update paw.state.data.login
	console.groupCollapsed( "Post Authentification for standard on :  https://" + pwa.state.data.ctx.urlbackoffice + "/users/login param data", data )

	logger.info( 'header de login', pwa.state.data.headers )
	let auth;
	try {
		auth = await axios.post( `https://${pwa.state.data.ctx.urlbackoffice }/users/login`, data, {
			headers: pwa.state.data.headers
		} );
		logger.info( "retour de login successfull ", auth );
		//Maj variable globale authentifié
		pwa.state.data.headers.xpaganid = auth.data.payload.data.UUID;
		pwa.state.data.headers.xauth = auth.data.payload.data.TOKEN;
		pwa.state.data.headers.xtribe = auth.data.payload.data.tribeid;
		pwa.state.data.headers.xworkon = auth.data.payload.data.tribeid;
		// Save local authentification uuid/token info user
		pwa.state.data.login.user = auth.data.payload.data;
		//request a refresh after a login
		pwa.state.data.ctx.refreshstorage = true;
		pwa.state.save();
		//alert( 'pwa.state.save() fait avec uuid' + pwa.state.data.headers.xpaganid )
		console.groupEnd();
		return true;
	} catch ( err ) {
		if( err.response ) { logger.info( "resp", err.response.data ) }
		if( err.request ) { logger.info( "req", err.request.data ) }
		logger.info( 'erreur de login reinit de rememberMe', err )
		pwa.state.data.login.rememberMe = {};
		document.querySelector( "#signin p.msginfo" )
			.innerHTML = document.querySelector( "#signin [data-msgko]" )
			.getAttribute( 'data-msgko' );
		console.groupEnd();
		return false;
	}
};
pwa.auth.logout = function () {
	logger.info( "remove ", pwa.state.data.ctx.website );
	localStorage.removeItem( pwa.state.data.ctx.website );
	window.location.href = "/";
}
pwa.auth.login = async function () {
	/*
	Check login/psw
	see auth.mustache & data_auth_lg.json for parameters
	Context info used:
	#signin p.msginfo contain message interaction with user
	#signin data-msgok data-msgko
	#signin button[data-routeto] is a redirection if authentification is successful
	*/
	document.querySelector( '#signin p.msginfo' )
		.innerHTML = "";
	const data = {
		LOGIN: document.querySelector( "#signin input[name='login']" )
			.value,
		PASSWORD: document.querySelector( "#signin input[name='password']" )
			.value
	}
	logger.info( 'check password', checkdata.test.password( "", data.PASSWORD ) )
	if( data.LOGIN.length < 4 || !checkdata.test.password( "", data.PASSWORD ) ) {
		/*$("#loginpart p.msginfo")
		.html("")
		  .fadeOut(2000)*/
		document.querySelector( '#signin p.msginfo' )
			.innerHTML = document.querySelector( '#signin [data-msgko]' )
			.getAttribute( 'data-msgko' );
	} else {
		if( document.querySelector( "[name='rememberme']" )
			.checked ) {
			pwa.state.data.login.rememberMe = data;
		}
		if( await pwa.auth.authentification( data ) ) {
			logger.info( 'Authentification VALIDE' )
			document.querySelector( '#signin p.msginfo' )
				.innerHTML = document.querySelector( "#signin [data-msgok]" )
				.getAttribute( 'data-msgok' );
			//state l'état isAuthenticated et check la route
			pwa.state.data.login.isAuthenticated = true;
			pwa.state.save();
			logger.info( pwa.state.data.login )
			logger.info( 'Auth ok route to ', document.querySelector( '#signin button[data-routeto]' )
				.getAttribute( 'data-routeto' ) );
			pwa.auth.route( document.querySelector( '#signin button[data-routeto]' )
				.getAttribute( 'data-routeto' ) );
		}
	}
};
pwa.auth.register = async function ( event ) {
	event.preventDefault();
	// gérer la cration du user
}
pwa.auth.forgetpsw = async function ( event ) {
	event.preventDefault();
	const tribeid = $( ".loginregister" )
		.getAttribute( "data-tribeid" );
	const email = $( '.forgetpsw .email' )
		.val();
	logger.info( `Reinit email: ${email} for tribeid: ${tribeid}` )
	try {
		logger.info( `https://${pwa.state.data.ctx.urlbackoffice }/users/getlinkwithoutpsw/${email}` )
		const reinit = await axios.get( `https://${pwa.state.data.ctx.urlbackoffice }/users/getlinkwithoutpsw/${email}`, {
			headers: pwa.state.data.headers
		} )
		$( "#forgetpswpart p.msginfo" )
			.html( "Regardez votre boite email" );
		return true;
	} catch ( er ) {
		logger.info( "Pb d'accès au back check apiamaildigit" )
		return false;
	}
};
