"use strict";
var pwa = pwa || {};
/*
FROM ndda/plugins/maildigitcreator/appjs/state.js
Manage state of the webapp
author: Phil Colzy - yzlocp@gmail.com
____________________________
pwa.state.save(): save in localstorage pwa.state.data avec le Nom du projet
____________________________
pwa.state.update(): update localstorage data from referential version
____________________________
pwa.state.ready(callback): await DOM loaded before running the callback
____________________________
pwa.state.refresh(): check if newversion of webapp to refresh page for dev purpose (do not use to refresh data)
____________________________
pwa.state.route(); check url and reroute it to function(urlparameter) or hide show part into a onepage website.
____________________________
pwa.state.loadfile({key:url},'dest') store in pwa.state.data.dest.key= file from url await all key to store result
___________________________
pwa.state.confdev() if ENV is dev then change urlbase for axios to looking for relevant file and refresh at a frequency pwa.state.refresh()

*/
//--##
pwa.state = {};

pwa.state.refresh = () => {
	//console.warn(`Lance le refresh de${pwa.state.env.page}`)
	//console.warn( 'ggg', pwa.state.data.ctx.urlbase )
	const currenthtml = location.pathname.split( '/' )
		.at( -1 )
		.replace( '.html', '.json' );
	//logger.info( currenthtml )
	axios.get( ` ${pwa.state.data.ctx.urlbase}/static/lastchange/${currenthtml}` )
		.then(
			data => {
				//logger.info( data.data.time, pwa.state.data.ctx.version )
				if( data.data.time > pwa.state.data.ctx.version ) {
					//logger.info( "reload la page pour cause de lastchange detecté" );
					pwa.state.data.ctx.version = data.data.time;
					pwa.state.data.ctx.refreshstorage = true;
					pwa.state.save();
					location.reload();
				} else {
					//logger.info( 'nothing change' )
				}
			},
			error => {
				logger.info( error );
			}
		);
};
pwa.state.ready = callback => {
	// Equivalent of jquery Document.ready()
	// in case the document is already rendered
	if( document.readyState != "loading" ) callback();
	// modern browsers
	else if( document.addEventListener )
		document.addEventListener( "DOMContentLoaded", callback );
	// IE <= 8
	else
		document.attachEvent( "onreadystatechange", function () {
			if( document.readyState == "complete" ) callback();
		} );
};
pwa.state.route = async () => {
	/* Allow to create dynamic content
 ?action=pwa object&id=&hh& => pwa.action("?action=pwa object&id=&hh&")
 ex: ?action=test.toto&id=1&t=123
 Each function that can be called have to start with
 if (e[1]=="?"){
  const urlpar = new URLSearchParams( loc.search );
	Then set param with urlpar.get('variable name')
  }
	 OR ?pagemd=name used into .html (div)
   Then it hide all <div class="pagemd" and show the one with <div id="page"+name
 */
	console.groupCollapsed( `pwa.state.route with window.location` );
	logger.info( 'List of pwa available ', Object.keys( pwa ) );
	if( !pwa.auth ) {
		logger.info( 'Warning, no auth.js, not a pb if no authentification need, if not check js order to be sur auth.js load before state.js' )
	} else {
		// check if still authenticated
		if( pwa.state.data.login.isAuthenticated ) {
			pwa.state.data.login.isAuthenticated = await pwa.auth.isAuthenticate();
		}
		//check if need authentification to show this page
		if( pwa.state.data.ctx.pageneedauthentification && !pwa.state.data.login.isAuthenticated ) {
			logger.info( 'reload page cause not auth and page require an auth' )
			window.location = `${pwa.state.data.ctx.pageredirectforauthentification}_${pwa.state.data.ctx.lang}.html`;
		}
	}
	const loc = window.location;
	if( loc.search ) {
		logger.info( Object.keys( pwa ) )
		const urlpar = new URLSearchParams( loc.search );
		if( urlpar.get( 'action' ) ) {
			const act = 'pwa.' + urlpar.get( 'action' ) + '("' + loc.search + '")';
			try {
				eval( act );
				logger.info( 'Specific action request to pwa.' + act )
			} catch ( err ) {
				logger.info( err )
				console.error( `You request ${act}, this action does not exist ` );
				alert( `Sorry but you have no access to ${act}, ask your admin` );
			}
		}
		let pgid = "pageindex"
		if( urlpar.get( 'pagemd' ) ) {
			pgid = "page" + urlpar.get( 'pagemd' )
		}
		//route to page content
		Array.from( document.getElementsByClassName( "pagemd" ) )
			.forEach( e => {
				logger.info( "detect pagemd", e.getAttribute( 'data-url' ) );
				e.classList.add( "d-none" );
			} );
		if( document.getElementById( pgid ) ) {
			document.getElementById( pgid )
				.classList.remove( 'd-none' );
		}
	}
	console.groupEnd();
	// If pwa.main exist then start pwa.main.init();
	if( pwa.main ) pwa.main.init();
}
pwa.state.loadfile = async ( list, dest ) => {
	// load external file if flag pwa.state.data.ctx.refreshstorage is true from pwa.state.refresh();
	//from list = {name:url} request are done with ctx.urlbase/url and store in localstorage pwa.state.data[dest][name]=data
	// if dest=='js' then it eval the js and store origin in pwa.state.data.js={name:url}
	//For at true refreshstorage if destination pwa.state.dest does not exist

	//logger.info( 'list', list )
	//logger.info( 'pwa.state.data.ctx.refreshstorage', pwa.state.data.ctx.refreshstorage )
	if( pwa.state.data.ctx.refreshstorage || !pwa.state.data[ dest ] || Object.keys( pwa.state.data[ dest ] )
		.length == 0 ) {
		if( !pwa.state.data[ dest ] ) pwa.state.data[ dest ] = {};
		try {
			let reqname = [];
			let reqload = [];
			for( const [ k, v ] of Object.entries( list ) ) {
				if( !pwa.state.data[ dest ][ k ] || pwa.state.data.ctx.refreshstorage ) {
					// if still not exist or refresstorage is set to true then add to load
					//@TODO check it works well on production
					reqname.push( k );
					reqload.push( v );
				}
			};
			//logger.info( pwa.state.data.ctx.urlbase, reqload )
			let resload = await Promise.all( reqload.map( r => {
				if( dest == 'tpldata' ) r = `${r}_${pwa.state.data.ctx.lang}.json`;
				return axios.get( `${pwa.state.data.ctx.urlbase}/${r}`, { headers: pwa.state.data.headers } )
			} ) );
			resload.forEach( ( d, i ) => {
				pwa.state.data[ dest ][ reqname[ i ] ] = d.data;
				pwa.state.save();
			} )
		} catch ( err ) {
			console.error( 'FATAL ERROR check that list exist remove if not', list, err.message )
		}
	}
};

pwa.state.save = function () {
	localStorage.setItem( pwa.state.data.ctx.website, JSON.stringify( pwa.state.data ) );
};
pwa.state.update = async function () {
	const domhtml = document.querySelector( "html" );
	const ctx = {
		tribeid: domhtml.getAttribute( 'data-tribeid' ),
		website: domhtml.getAttribute( "data-website" ),
		nametpl: domhtml.getAttribute( "data-nametpl" ),
		pagename: domhtml.getAttribute( "data-pagename" ),
		urlbackoffice: domhtml.getAttribute( "data-urlbackoffice" ),
		pageneedauthentification: true,
		pageredirectforauthentification: "",
		lang: domhtml.getAttribute( "lang" ),
		env: domhtml.getAttribute( "data-env" ),
		version: domhtml.getAttribute( "data-version" ),
		refreshstorage: false
	}
	if( !domhtml.getAttribute( 'data-pageneedauthentification' ) || domhtml.getAttribute( 'data-pageneedauthentification' ) == 'false' ) {
		ctx.pageneedauthentification = false;
	}
	if( domhtml.getAttribute( 'data-pageforauthentification' ) ) {
		ctx.pageforauthentification = domhtml.getAttribute( 'data-pageforauthentification' );
	}
	console.groupCollapsed( `update pwa.state with html attribut or from localstorage into ${ctx.website}` );
	logger.info( 'html context:', ctx );
	if( localStorage.getItem( ctx.website ) ) {
		pwa.state.data = JSON.parse( localStorage.getItem( ctx.website ) );
		//alert( 'recupere pwa.state.data xpaganid:' + pwa.state.data.headers.xpaganid )
	}
	if( !( pwa.state.data && pwa.state.data.ctx.tribeid == ctx.tribeid && pwa.state.data.ctx.website == ctx.website ) ) {
		logger.info( " reinitialise localstorage cause work on a different project or first access" );
		delete pwa.state.data;
		localStorage.removeItem( ctx.website )
	}
	/*
	if( pwa.state.data && statejson.data.app.version && ( parseInt( pwa.state.data.app.version ) < parseInt( statejson.data.app.version ) ) ) {
		// le numero de version en mémoire est < au numero disponible sur le serveur
		// force un logout pour reinitialiser les menus
		delete pwa.state.data;
		localStorage.removeItem( pwa.PROJET )
	}
	*/
	if( !pwa.state.data ) {
		// No localstorage available et one by default
		pwa.state.data = {
			ctx,
			login: {
				isAuthenticated: false,
				user: {},
				rememberMe: {}
			},
			headers: {
				'xauth': '1',
				'xpaganid': '1',
				'xtribe': ctx.tribeid,
				'xlang': ctx.lang,
				'xworkon': ctx.tribeid,
				'xapp': `${ctx.tribeid}:${ctx.website}`
			}
		}
		logger.info( 'load new state.data', pwa.state.data )
	}
	// Check if external component need to be load
	const app = `${pwa.state.data.ctx.tribeid}:${pwa.state.data.ctx.website}`;
	if( pwa.state.data.login.isAuthenticated &&
		pwa.state.data.login.user.ACCESSRIGHTS.app[ app ] &&
		pwa.state.data.login.user.ACCESSRIGHTS.app[ app ].js
	) {
		logger.info( 'tttt', pwa.state.data.login.isAuthenticated, pwa.state.data.login.user.ACCESSRIGHTS.app[ app ].js )
		pwa.state.data.login.user.ACCESSRIGHTS.app[ app ].js.some( ( u ) => {
			logger.info( `load from user ACCESSRIGHTS app[${pwa.state.data.ctx.tribeid}:${pwa.state.data.ctx.website}].js  : ${u}` )
			const script = document.createElement( 'script' );
			script.src = u;
			script.async = false;
			document.body.appendChild( script );
		} );
	}
	//Check dev to set parameter to simplify dev app
	//check in confdev version and set pwa.state.data.ctx.refreshstorage at true if new version
	pwa.state.confdev();
	console.groupEnd();
	pwa.state.route();
	pwa.state.save();
};
pwa.state.confdev = () => {
	if( pwa.state.data.ctx.env == 'dev' ) {
		pwa.state.data.ctx.urlbase = `/space/${pwa.state.data.ctx.tribeid}/${pwa.state.data.ctx.website}/dist`;
		// check each 3 sec if new version to reload
		setInterval( "pwa.state.refresh()", 3000 );
	} else {
		//pwa.state.axios = axios.create();
		pwa.state.data.ctx.urlbase = "/";
		// check and refresh if new version only one time
		pwa.state.refresh();
	}
}
// Refresh browser state if exist else get pwa.state defaults
pwa.state.ready( pwa.state.update );
