"use strict";
var pwa = pwa || {};
/*
Manage referentials for a tribeid




*/
//--##
pwa.referential = {};
pwa.referential.content = `
<div class="row gap-20 masonry pos-r">
  <div class="blocA masonry-item col-md-6">
    <div class="bgc-white p-20 bd">
      <h6 class="c-grey-900">Affiche json</h6>
      <div id="jsoneditor" class="jsoneditor">
      </div>
    </div>
  </div>
  <div class="blocB masonry-item col-md-6">
    <div class="bgc-white p-20 bd">
      <h6 class="c-grey-900">Changer son mot de passe</h6>
      <div class="formdata">
      </div>
    </div>
  </div>
</div>
`;
pwa.referential.set = async ( sourceref ) => {
	/*
	  @sourceref app (recupere le referentiel de l'application)
	             workon (recupere le referentiel du client id sur lequel on travail state.data.headers[X-workOn])
	  On alimente le referentiel ds localStorage
	    state.app.referentials = {menu:}
	 */
	console.groupCollapsed( 'Load pwa.referential.set with ', sourceref )
	//let reftoload;
	let savexworkon;
	if( sourceref == "app" ) {
		//reftoload = pwa.state.data.app.referentials
		// affecte le menu en fonction du profil
		console.assert( pwa.state.data.app.profil && pwa.state.data.app.profil[ pwa.state.data.userlogin.ACCESSRIGHTS.app[ `${pwa.tribeid}:${pwa.PROJET}` ] ], `profil de l app ${pwa.tribeid}:${pwa.PROJET} n'existe pas pour le user dans userlogin.ACCESSRIGHTS.app , verifier qu'on a bien pour cette app un menu correspondant` );
		const menuapp = pwa.state.data.app.profil[ pwa.state.data.userlogin.ACCESSRIGHTS.app[ `${pwa.tribeid}:${pwa.PROJET}` ] ].menu;
		if( !pwa.state.data.app.referentials.json[ menuapp ] ) {
			//on ajoute ce menu avec une version à O pour forcer sa mise à jour
			pwa.state.data.app.referentials.json[ menuapp ] = { version: 0 }
		}
		//set xworkon on tribeid where app is stored
		savexworkon = pwa.state.data.headers[ 'X-WorkOn' ];
		pwa.state.data.headers[ 'X-WorkOn' ] = pwa.tribeid
	}
	/* else if(sourceref == "xworkon") {
	  // on recupere le referentiel utile pour clientcon.json du xworkon pour le projet
	  reftoload = pwa.state.data.xworkon.referentials
	}*/
	// recupere les versions du clientconf.json
	const clientconfref = await axios.get( `${pwa.urlbackauth}/referentials/clientconf/referentials`, { headers: pwa.state.data.headers } );
	console.debug( 'clientconfref', clientconfref );
	for( const o of [ 'object', 'json', 'data' ] ) {
		console.debug( o )
		//update by adding or upgraded version if in dev or in prod and pwa.state.data[sourceref].referentials[type=object|json|data][nomref].version is upper than the local one
		// Take care app is load first with previous referential then need to refresh app to use the new version.
		if( !clientconfref.data.referentials[ o ] ) {
			clientconfref.data.referentials[ o ] = {};
		}
		//Warning do not use foreach in async cause foreach is not sync
		for( const r of Object.keys( clientconfref.data.referentials[ o ] ) ) {
			console.debug( r )
			if( !pwa.state.data.app.referentials[ o ][ r ] ) {
				// New referential added need to reload app to refresh app
				pwa.state.data.app.referentials[ o ][ r ] = { version: -1 };
			}
			if( pwa.MODE_ENV == "dev" || !( pwa.state.data.app.referentials[ o ][ r ].version == clientconfref[ o ][ r ].version ) ) {
				// alors nouvelle version à mettre à jour en dev on le fait systematiquement
				logger.info( `${pwa.urlbackauth}/referentials/content/${o}/${r}`, pwa.state.data.headers );
				const dataref = await axios.get( `${pwa.urlbackauth}/referentials/content/${o}/${r}`, { headers: pwa.state.data.headers } )
				if( dataref.status == 200 ) {
					logger.info( `${o} - ${r}`, dataref.data )
					pwa.state.data[ sourceref ].referentials[ o ][ r ] = dataref.data;
					pwa.state.save()
				} else {
					logger.info( `ERREUR de recuperation de referentiel ${o} ${r}` )
				}
			}
		}
		// we remove from local if nomref disapear of app clientconfref.data.referential
		Object.keys( pwa.state.data[ sourceref ].referentials[ o ] )
			.forEach( r => {
				if( !clientconfref.data.referentials[ o ] ) {
					delete pwa.state.data[ sourceref ].referentials[ o ];
					pwa.state.save();
				}
			} )
	};
	if( sourceref == "app" ) {
		// on remet le xworkon en cours
		pwa.state.data.headers[ 'X-WorkOn' ] = savexworkon;
	}
	console.groupEnd();
};
pwa.referential.forceupdate = () => {
	axios.get( `${pwa.urlbackauth}/referentials/updatefull`, {
			headers: pwa.state.data.headers
		} )
		.then( data => {
			alert( data.status )
		} )
}
// GUI to manage referential
pwa.referential.setting = async ( objecttype ) => {
	// Convert location.search to get objecttype
	const urlpar = new URLSearchParams( objecttype );
	objecttype = ( urlpar.get( 'objecttype' ) ) ? urlpar.get( 'objecttype' ) : objecttype;

	const tpleditor = `
    <div class="input-group mb-3" data-idref="{{id}}">
      <button class="btn btn-outline-primary actionobject save" >
          {{{btnsave}}}
      </button>
      <button class="btn btn-outline-primary actionobject delete" >
          {{{btndelete}}}
      </button>
        <button class=" btn btn-outline-primary actionobject copy" >
         {{{btncopy}}}
        </button>
        <input type="text" class="form-control nameas" placeholder="{{{copyplaceholder}}}" >
       </div>
    </div>
    <div class="jsoneditor mb-3"></div>
      `;

	console.groupCollapsed( `load referentials setting for ${objecttype}` );
	//reinit submenuitems
	pwa.state.data.app.referentials.json.referentialsetting.submenuitems = [];
	//Requested directly the back warranty to get always the last updated referential
	const data = await axios.get( `${pwa.urlbackauth}/referentials/contentlist/${objecttype}`, {
		headers: pwa.state.data.headers
	} );
	logger.info( "Liste des referentiels ", data.data )
	let reqref = []
	let ref = []
	//init a temporary (opposite od state that is save) data to work on referential (each time referentials/object is load this variable is refresh)
	pwa.tmp = {};
	data.data.forEach( o => {
		reqref.push( axios.get( `${pwa.urlbackauth}/referentials/contentfull/${objecttype}/${o}`, {
			headers: pwa.state.data.headers
		} ) )
		ref.push( o );
	} );
	axios.all( reqref )
		.then( axios.spread( ( ...rep ) => {
			logger.info( rep )
			rep.forEach( ( d, i ) => {
				pwa.tmp[ ref[ i ] ] = d.data
				const submenuit = {
					active: "",
					groupinfo: ref[ i ],
					id: `referential${ref[i]}`,
					optionjsoneditor: {},
					onclick: `pwa.referential.save(event,'referential${ref[i]}')`,
					btnsave: pwa.state.data.app.referentials.json.referentialsetting.btnsave,
					btndelete: pwa.state.data.app.referentials.json.referentialsetting.btndelete,
					btncopy: pwa.state.data.app.referentials.json.referentialsetting.btncopy,
					copyplaceholder: pwa.state.data.app.referentials.json.referentialsetting.copyplaceholder,
					objecttype: objecttype
				};
				pwa.state.data.app.referentials.json.referentialsetting.submenuitems.push( submenuit )
			} );
			document.getElementById( 'maincontent' )
				.innerHTML = Mustache.render( document.getElementById( 'referential' )
					.innerHTML, pwa.state.data.app.referentials.json.referentialsetting );

			pwa.state.data.app.referentials.json.referentialsetting.submenuitems.forEach( tab => {
				document.getElementById( tab.id )
					.innerHTML = Mustache.render( tpleditor, tab );
				//logger.info( tab.id, tab )
				// Convert each div with formfieldtype to a form field set with value if exist and listen button to run callback
				pwa.referential.init( tab );
			} );
		} ) )
		.catch( err => {
			logger.info( "eeeee", err );
			const submenuit = {
				active: "",
				groupinfo: objecttype,
				id: `referential${objecttype}`,
				optionjsoneditor: {},
				onclick: `pwa.referential.save(event,'referential${objecttype}')`,
				data: { erreur: err }
			};
			pwa.state.data.app.referentials.json.referentialsetting.submenuitems.push( submenuit )
		} );
	console.groupEnd();
}

pwa.referential.init = ( tab ) => {
	const doctab = document.querySelector( `#${tab.id}` );
	const editor = new JSONEditor( doctab.querySelector( `.jsoneditor` ), tab.optionjsoneditor );
	console.table( tab )
	logger.info( tab.objecttype, tab.groupinfo )
	editor.set( pwa.tmp[ tab.groupinfo ] );
	editor.expandAll();
	// ajoute un listener sur btn pour faire axios post with editor.get()
	Array.from( doctab.querySelectorAll( '.save, .delete, .copy' ) )
		.forEach( act => {
			act.addEventListener( 'click', e => {
				e.preventDefault();
				logger.info( 'cliiiiiiiiiiiiiiiiiiiick', tab.id )
				if( e.target.classList.contains( 'save' ) ) {
					/*
					axios.put( `${pwa.urlbackauth}/referentials/content/${tab.objecttype}/${tab.groupinfo}`, editor.get(), {
							headers: pwa.state.data.headers
						} )
						.then( data => {
							logger.info( "affiche message done" );
						} )
						.catch( err => {
							logger.info( "affiche message err ", err )
						} );
            */
					logger.info( 'editor', editor.get() );
				}
				if( e.target.classList.contains( 'delete' ) ) {
					//axios.get( @tTODO la mise à jour du nouveau referentiel avec la version)
				}
				if( e.target.classList.contains( 'copy' ) ) {
					//@TODO create a new referential file localy from an existing one
				}
				/*logger.info( e.target.closest( '[data-idref]' )
					.getAttribute( 'data-idref' ) )
				logger.info( editor.get() );
				envoyer à axios et modifier pwa.state. en cours
        */
			} );
		} );
}

///////////////////////////////////////////////////////

pwa.referential.initold = async ( object ) => {
	$( '#mainContent' )
		.html( pwa.referential.content );
	// charge ul#menuleft
	// create the editor
	const container = document.getElementById( "jsoneditor" )
	const options = {}
	const editor = new JSONEditor( container, options )
	axios.get( `${pwa.urlbackauth}/referentials/content/object/${object}`, {
			headers: pwa.state.data.headers
		} )
		.then(
			( ref ) => { editor.set( ref.data ) },
			( error ) => {
				window.location.pathname == "/"
			} )
	// set json
	/*const initialJson = {
    "Array": [1, 2, 3],
    "Boolean": true,
    "Null": null,
    "Number": 123,
    "Object": { "a": "b", "c": "d" },
    "String": "Hello World"
  }
  editor.set(initialJson)
*/
	// get json
	const updatedJson = editor.get()
	logger.info( 'updatedJson', updatedJson )
}
