const fs = require( 'fs' );
const formidable = require( 'formidable' );
const jsonfile = require( 'jsonfile' );
const path = require( 'path' );
const glob = require( 'glob' );
const mustache = require( 'mustache' );
const moment = require( 'moment' );
// Check if package is installed or not to pickup the right config file
const config = require( '../tribes/townconf.js' );


const Tags = {};
/*
Keyword definition:

id:  b64 encoded field that can be : email , uuid
tribeid: apiamaildigit client Id, (a folder /tribes/tribeid have to exist)
email: identifiant of a person
uuid: identifiant o
 contact database
operationId: code name of an operation
messageId: code name of an templatesource have to exist in /datashared/templatesource/generic/messageId

*/
/*
Manage tag data collection
Popup survey manager
*/
Tags.info = ( data, req ) => {
	//logger.info('headers:', req.headers)
	/*logger.info('hostname', req.hostname)
	logger.info('req.ip', req.ip)
	logger.info('req.ips', req.ips)
	logger.info('req key', Object.keys(req))
	*/
	//logger.info('req.rawHeaders', req.body)
	data.useragent = `${req.headers['user-agent']}__${req.headers['accept-language']}__${req.headers['accept-encoding']}__${req.headers['connection']}`;
	data.ips = req.ips;
	data.ip = req.ip;
	data.proxyip = req.connection.remoteAddress;
	data.cookie = ""
	Object.keys( req.headers )
		.forEach( k => {
			if( ![ 'user-agent', 'accept-language', 'accept-encoding', 'connection' ].includes( k ) ) {
				data.cookie += `${k}__${req.headers['cookie']}|`
			}
		} )
	//data.cookie = `${req.headers['cookie']}__${req.headers['upgrade-insecure-requests']}__${req.headers['if-modified-since']}__${req.headers['if-no-match']}__${req.headers['cache-control']}`;
	return data
}
Tags.getfile = ( filename, req ) => {
	const infotg = filename.split( '__' );
	if( infotg.length < 3 && !fs.existsSync( `${config.tribes}/${infotg[1]}` ) ) {
		return {
			status: 400,
			payload: { info: [ 'fileUnknown' ], model: 'UploadFiles' }
		}
	}
	if( infotg[ 0 ] == "imgtg" ) {
		jsonfile.writeFile( `${config.tribes}/${infotg[1]}/tags/imgtg/${Date.now()}.json`, Tags.info( { filename: filename, messageId: infotg[ 2 ], operationId: infotg[ 3 ], identifiant: infotg[ 4 ] }, req ), function ( err ) {
			if( err ) {
				logger.info( `Erreur de sauvegarde de tag:${filename}` )
			}
		} );
		return {
			status: 200,
			payload: { moreinfo: "Declenche tag", filename: `${config.mainDir}/public/imgtg.png` }
		}
	}
	return { status: 404, payload: {} }
}
Tags.savehits = ( req ) => {
	if( !fs.existsSync( `${config.tribes}/${req.params.tribeid}` ) ) {
		logger.info( `Erreur d'envoi de tag sur ${req.params.tribeid} pour ${req.params.r}` );
		return false;
	} else {
		const info = JSON.parse( JSON.stringify( req.body ) );
		jsonfile.writeFile( `${config.tribes}/${req.params.tribeid}/tags/hits/${Date.now()}.json`, Tags.info( info, req ), function ( err ) {
			if( err ) {
				logger.info( `Erreur de sauvegarde de tag pour ${req.params.tribeid} check si /tags/hits et /tags/imgtg exist bien ` )
			}
		} );
	}
	return true;
}
Tags.dataloadstat = ( tribeid ) => {
	/*
	@TODO à appeler via une route pour agregation de tag
	@TODO ajouter la suppression des fichiers hits traités qd le prog aura fait ses preuves en prod
	@TODO corriger la prod pour que l'ip passe

	Si on recharge plusieurs fois un hits (on ne le comptabilise pas si même r et même timestamps)

	Manage tag info to agregate by user and by statistique
	stats/data.json = {r:{
	                      info:{useragent:"",ip:[]},
	                      data:[ [timestamps, tit, cookie] ]
	                      }
	                    }
	stats/graph.json = {"graphYears": {AAAA:#visites,"years":[AAAA,AAAA]},
	                     "graphMonths": {AAAA:{"Jan":#visites,..},"monthsLabels":["Jan",..],"years":[AAAA,]},
	                     "graphDaysOfWeek":{"labels":["Sun","Mon",...],"Sun":#visites},
	                     "graphHoursOfDay":{"labels":["OOh","01h",...],"00h":#visites}
	                    }
	 Pour tester des evolutions ou un client en dev (recuperer son repertoire de prod /tags )
	  ajouter Tags.dataloadstat('yes');
	  NODE_ENV=dev node ./models/Tags.js
	*/
	const agrege = {
		data: {},
		graph: {
			visites: {
				graphYears: { years: [] },
				graphMonths: {
					years: [],
					monthsLabels: []
				},
				graphMonths: {
					years: [],
					monthsLabels: []
				},
				graphDayOfWeek: { labels: [] },
				graphHourOfDay: { labels: [] }
			},
			visitors: {
				graphMonths: {
					years: [],
					monthsLabels: []
				}
			}
		}
	};
	try {
		agrege.data = jsonfile.readfileSync( `${config.tribes}/${tribeid}/tags/stats/data.json`, "utf-8" );
		agrege.graph = jsonfile.readfileSync( `${config.tribes}/${tribeid}/tags/stats/graph.json`, "utf-8" );
	} catch ( err ) {
		logger.info( "ATTENTION tag reinitialisé en data.json et graph.json, s'il s'agit de 1ere connexion pas de pb. Le risque est de perdre les tag historiques" )
		//return { status: 503, payload: { info: ['Errconfig'], model: 'Tags', moreinfo: `Il manque un ${config.tribes}/${tribeid}/tags/stats/data.json ou stats/graph.json` } }
	}
	glob.sync( `${config.tribes}/${tribeid}/tags/hits/*` )
		.forEach( f => {
			const hit = jsonfile.readFileSync( f );
			const ts = parseInt( path.basename( f )
				.split( ".json" )[ 0 ] );
			//logger.info(moment(ts).format('DD-MM-YYYY h:mm:ss'));
			const tsm = moment( ts )
			const year = tsm.format( 'YYYY' );
			const month = tsm.format( 'MMM' );
			const dayow = tsm.format( 'ddd' );
			const hourod = tsm.format( 'HH' ) + "h";
			let newvisitor = false;
			let alreadydone = false;
			//logger.info(hit.r, ts)
			// Agrege data pour # visiteur vs # de visiteur
			if( agrege.data[ hit.r ] ) {
				if( !agrege.data[ hit.r ].data.some( el => el[ 0 ] == ts ) ) {
					//evite de charger plusieurs fois le même
					agrege.data[ hit.r ].data.push( [ ts, hit.tit, hit.cookie ] )
				} else {
					alreadydone = true;
				}
			} else {
				newvisitor = true;
				agrege.data[ hit.r ] = {
					info: { useragent: hit.useragent, ip: [ hit.ip ] },
					data: [
            [ ts, hit.tit, hit.cookie ]
          ]
				}
			}
			if( !alreadydone ) {
				if( newvisitor ) {
					//traite Month
					if( !agrege.graph.visitors.graphMonths[ year ] ) {
						agrege.graph.visitors.graphMonths[ year ] = {}
						agrege.graph.visitors.graphMonths.years.push( year )
					}
					if( agrege.graph.visitors.graphMonths[ year ][ month ] ) {
						agrege.graph.visitors.graphMonths[ year ][ month ] += 1
					} else {
						agrege.graph.visitors.graphMonths[ year ][ month ] = 1
						agrege.graph.visitors.graphMonths.monthsLabels.push( month )
					}
				}
				//traite graphe Year #visite
				if( agrege.graph.visites.graphYears[ year ] ) {
					agrege.graph.visites.graphYears[ year ] += 1
				} else {
					agrege.graph.visites.graphYears[ year ] = 1
					agrege.graph.visites.graphYears.years.push( year )
					agrege.graph.visites.graphMonths[ year ] = {}
					agrege.graph.visites.graphMonths.years.push( year )
				}
				//traite graphe Month
				if( agrege.graph.visites.graphMonths[ year ][ month ] ) {
					agrege.graph.visites.graphMonths[ year ][ month ] += 1
				} else {
					agrege.graph.visites.graphMonths[ year ][ month ] = 1
					agrege.graph.visites.graphMonths.monthsLabels.push( month )
				}
				//traite graphe Days of week
				if( agrege.graph.visites.graphDayOfWeek[ dayow ] ) {
					agrege.graph.visites.graphDayOfWeek[ dayow ] += 1
				} else {
					agrege.graph.visites.graphDayOfWeek[ dayow ] = 1
					agrege.graph.visites.graphDayOfWeek.labels.push( dayow )
				}
				//traite graphe Hour of day
				if( agrege.graph.visites.graphHourOfDay[ hourod ] ) {
					agrege.graph.visites.graphHourOfDay[ hourod ] += 1
				} else {
					agrege.graph.visites.graphHourOfDay[ hourod ] = 1
					agrege.graph.visites.graphHourOfDay.labels.push( hourod )
				}
			}
		} )
	jsonfile.writeFileSync( `${config.tribes}/${tribeid}/tags/stats/data.json`, agrege.data, 'utf-8' );
	jsonfile.writeFileSync( `${config.tribes}/${tribeid}/tags/stats/graph.json`, agrege.graph, 'utf-8' );
	return { status: 200, payload: { info: [ 'Statsupdated' ], model: 'Tags' } }
}
//logger.info(Tags.dataloadstat('yes'));
/*const ar = [
  [1, 1],
  [1, 2]
]
logger.info(ar.some(el => el[0] == 1 && el[1] == 1))
logger.info(ar.some(el => el == [1, 3]))
*/
module.exports = Tags;
