/*
After state.js / auth.js and all external js lib
Load

*/
var pwa = pwa || {};
pwa.main = pwa.main || {};
pwa.main.tpldata = pwa.main.tpldata || {};
pwa.main.tpl = pwa.main.tpl || {};
pwa.main.tpldata = pwa.main.tpldata || {};
pwa.main.ref = pwa.main.ref || {};

pwa.main.tpl.appsidebarmenu = 'static/components/appmesa/appsidebarmenu.mustache';
pwa.main.tpl.apptopbarmenu = 'static/components/appmesa/apptopbarmenu.mustache';
pwa.main.tpldata.sidebar = `static/components/appmesa/data_sidebar`;
pwa.main.tpldata.topbar = `static/components/appmesa/data_topbar`;
pwa.main.tpldata.topbarLogin = `static/components/appmesa/data_topbarLogin`;

pwa.main.init = () => {
	const isempty = ( obj ) => {
		return obj && Object.keys( obj )
			.length === 0 && obj.constructor === Object
	}

	// Load public env tpl & tpldata
	//Manage action depending of html file currently show
	const currenthtml = location.pathname.split( '/' )
		.at( -1 );
	console.groupCollapsed( `pwa.main.init for ${currenthtml} html page` );
	if( currenthtml.includes( 'app_' ) ) {
		pwa.main.loadmenu()
	}
	// To manage if authenticated or not in a simple way
	/*
		if( pwa.state.data.login.isAuthenticated ) {
			//authenticated
			// identity inside pwa.state.login.user
		}else{
			//anonymous
			// can check if the url is relevant with isAuthenticated
			//route to app if exist data-routo into a signin
			//pwa.auth.route( document.querySelector( '#signin button[data-routeto]' ).getAttribute( 'data-routeto' ) );
			// add and load dynamicaly the gui.js plugin if user that request it has access
		}
	*/
	console.groupEnd();
};

pwa.main.loadmenu = async () => {
	logger.info( 'pwa.main.loadmenu running' );
	logger.info( 'Status of pwa.state.data.login.isAuthenticated =', pwa.state.data.login.isAuthenticated );
	let datasidebar, datatopbar;
	/* Build datasidebar and datatopbar depending of list of module allowed by user in his ACCESSRIGHTS profil.
	 app[`${pwa.state.data.ctx.tribeid}:${pwa.state.data.ctx.website}`].js;

  */
	//logger.info( 'List of tpldata', pwa.main.tpldata )
	//logger.info( 'List of tpl', pwa.main.tpl )
	logger.info( `run pwa.state.loadfile with pwa.state.data.ctx.refreshstorage = ${pwa.state.data.ctx.refreshstorage} if true=> refresh anyway, if false refresh only if dest.name does not exist` );
	await pwa.state.loadfile( pwa.main.tpl, 'tpl' );
	await pwa.state.loadfile( pwa.main.tpldata, 'tpldata' );
	datasidebar = pwa.state.data.tpldata.sidebar;
	//any tpldata containing sidebar in pwa.state.data.tpldata is add to sbgroupmenu to be available
	Object.keys( pwa.state.data.tpldata )
		.filter( m => ( m != 'sidebar' && m.includes( 'sidebar' ) ) )
		.some( k => {
			datasidebar.sbgroupmenu.push( pwa.state.data.tpldata[ k ] )
		} );
	//merge les menu topbar
	datatopbar = pwa.state.data.tpldata.topbar;
	if( pwa.state.data.login.isAuthenticated ) {
		// update user information if needed
		datatopbar.name = pwa.state.data.login.user.LOGIN;
		datatopbar.avatarimg = pwa.state.data.login.user.AVATARIMG;
		delete pwa.state.data.tpldata.topbarLogin;
		pwa.state.save();
	}
	datatopbar.menuprofil = [];
	Object.keys( pwa.state.data.tpldata )
		.filter( m => ( m != 'topbar' && m.includes( 'topbar' ) ) )
		.some( k => {
			datatopbar.menuprofil.push( pwa.state.data.tpldata[ k ] )
		} );
	if( pwa.state.data.tpl.appsidebarmenu ) {
		document.querySelector( "#sidebar" )
			.innerHTML = Mustache.render( pwa.state.data.tpl.appsidebarmenu, datasidebar )
		document.querySelector( "#navbar" )
			.innerHTML = Mustache.render( pwa.state.data.tpl.apptopbarmenu, datatopbar )
		//active les icones svg de feather
		feather.replace();
		//active scroll presentation + sidebar animation
		pwa.main.simplebar();
		pwa.main.clickactive();
	};
};

//////////////////////////////////////////////////////
// simplebar
//////////////////////////////////////////////////////
pwa.main.simplebar = () => {
	const simpleBarElement = document.getElementsByClassName( "js-simplebar" )[ 0 ];

	if( simpleBarElement ) {
		/* Initialize simplebar */
		new SimpleBar( document.getElementsByClassName( "js-simplebar" )[ 0 ] )

		const sidebarElement = document.getElementsByClassName( "sidebar" )[ 0 ];
		const sidebarToggleElement = document.getElementsByClassName( "sidebar-toggle" )[ 0 ];

		sidebarToggleElement.addEventListener( "click", () => {
			sidebarElement.classList.toggle( "collapsed" );

			sidebarElement.addEventListener( "transitionend", () => {
				window.dispatchEvent( new Event( "resize" ) );
			} );
		} );
	}
}
/////////////////////////////////////////////////////////
// manage click effect
////////////////////////////////////////////////////////
pwa.main.clickactive = () => {
	const cleanactive = () => {
		const el = document.querySelectorAll( '.sidebar-item' )
		for( var i = 0; i < el.length; i++ ) {
			//logger.info( 'clean', el[ i ].classList )
			el[ i ].classList.remove( 'active' );
		}
	}
	document.addEventListener( "click", ( e ) => {
		logger.info( 'click', e );
		if( e.target.classList.contains( 'sidebar-link' ) ) {
			cleanactive();
			e.target.closest( '.sidebar-item' )
				.classList.add( 'active' );
			// remonte au menu au dessus si existe
			e.target.closest( '.sidebar-item' )
				.closest( '.sidebar-item' )
				.classList.add( 'active' );
		}
	} );
	// If enter run the research
	document.getElementById( 'globalsearch' )
		.addEventListener( 'keypress', ( e ) => {
			if( e.keyCode == 13 ) {
				pwa.search.req( 'globalsearch' );
				e.preventDefault();
			}
		} )
};
