const fs = require( 'fs-extra' );
const jsonfile = require( 'jsonfile' );
const glob = require( 'glob' );
const path = require( 'path' );
const moment = require( 'moment' );
const axios = require( 'axios' );
const scrapeit = require( 'scrape-it' );
const cheerio = require( 'cheerio' );
const Mustache = require( 'mustache' );
const qrcode = require( 'qrcode' );

// Check if package is installed or not to pickup the right config file

const config = require( '../tribes/townconf.js' );

/*
Model that will process actions plan for each client like sending email campain, or anything that
are plan in /tribes/tribeid/actions/todo
*/
const Cards = {}; //require('../../models/Cards');
const Contracts = {};
/*
Send if envoicampain a liste of email in param.msg.destperso with param.headers
if not envoicampain, it just return a test about what to send
@param = {headers, msg:{destperso}}
*/
Contracts.sendcampain = async ( param, envoicampain ) => {
	if( envoicampain ) {
		// Carefull w the action post outputs/msg just wait the feedback of the 1st message
		const retcampain = await axios.post( 'https://mail.maildigit.fr/outputs/msg', param.msg, {
			headers: param.headers
		} );
		if( retcampain.status !== 200 ) {
			logger.info( "err", retcampain.payload.moreinfo );
			fs.appendFileSync( `${config.tribes}/log_erreurglobal.txt`, moment( new Date() )
				.format( 'YYYYMMDD HH:mm:ss' ) + ' - IMPOSSIBLE TO SEND CAMPAIN TODO for :' + param.tribeid + ' -- ' + retcampain.payload.moreinfo + '\n', 'utf-8' );
		};
		return retcampain;
	} else {
		// permet de tester ce qu'il y a à envoyer
		let premieremail = "";
		for( let i = 0; i < param.msg.destperso.length; i++ ) {
			premieremail += param.msg.destperso[ 0 ].email + ",";
		}
		return {
			status: 201,
			payload: {
				info: [ 'simplecomptage' ],
				model: 'Contracts',
				moreinfo: "#email: " + param.msg.destperso.length + " - 5 1st emails: " + premieremail
			}
		};
	}
}
Contracts.initActiontodo = async ( envoie ) => {
	const datedeb = moment( new Date() )
		.format( 'YYYYMMDD HH:mm:ss' );
	let todo, actiondone;
	let log = {
		nbaction: 0,
		nbactionexec: 0,
		nbactionerr: 0,
		actionlist: ""
	};
	const listclient = jsonfile.readFileSync( `${config.tribes}/tribeids.json` );
	for( let clid in listclient ) {
		logger.info( listclient[ clid ] );
		let listaction = glob.sync( `${config.tribes}/${listclient[clid]}/actions/todo/*.json` );
		for( let action in listaction ) {
			logger.info( listaction[ action ] )
			log.nbaction++;
			todo = jsonfile.readFileSync( listaction[ action ] );
			let passdate = true;
			// currentdate doit etre après la startDate si existe et avant valideuntilDate si existe
			// logger.info('test now est avant date start ', moment() < moment(todo.startDate, 'YYYYMMDD HH:mm:ss').toDate());
			if( todo.startDate && ( moment() < moment( todo.startDate, 'YYYYMMDD HH:mm:ss' )
					.toDate() ) ) {
				passdate = false;
			};
			// currentdate ne doit pas depasser la date de validité de la tache
			// logger.info('test now est après la date de validite ', moment() > moment(todo.validuntilDate, 'YYYYMMDD HH:mm:ss').toDate());
			if( todo.valideuntilDate && ( moment() > moment( todo.validuntilDate, 'YYYYMMDD HH:mm:ss' )
					.toDate() ) ) {
				passdate = false;
			};
			// currentdate
			if( passdate && todo.action && todo.error == "" ) {
				log.nbactionexec++;
				const actiondone = await Contracts[ todo.action ]( todo, envoie );
				todo.datesRun.push( moment( new Date() )
					.format( 'YYYYMMDD HH:mm:ss' ) );
				//logger.info("actiondone", actio  jsonfile.writeFileSyncndone);
				log.actionlist += "STATUS:" + actiondone.status + " -- " + listaction[ action ] + "\n";
				if( actiondone.status == 200 ) {
					todo.error = "";
				} else {
					log.nbactionerr++;
					todo.error += "status : " + actiondone.status + ' ' + actiondone.payload.moreinfo;
				};
				if( parseInt( todo.maxnumberoftime ) && todo.maxnumberoftime != "999" && ( todo.datesRun.length >= parseInt( todo.maxnumberoftime ) ) ) {
					//archive en done this triggeraction
					jsonfile.writeFileSync( listaction[ action ].replace( '/todo/', '/done/' ), todo, {
						spaces: 2
					} );
					fs.unlinkSync( listaction[ action ] );
				} else {
					jsonfile.writeFileSync( listaction[ action ], todo, {
						spaces: 2
					} );
				}
			} else {
				log.actionlist += "STATUS : not executed " + listaction[ action ] + "\n";
			};
		};
	};
	const trace = "###################### LOGS ####################\nSTART:" + datedeb + " END:" + moment( new Date() )
		.format( 'YYYYMMDD HH:mm:ss' ) + "\n nombre d'actions analysées : " + log.nbaction + " dont executées : " + log.nbactionexec + " dont en erreur: " + log.nbactionerr + "\n" + log.actionlist;
	fs.appendFileSync( `${config.tribes}/log.txt`, trace, 'utf-8' );
	return "done";
}
module.exports = Contracts;
