const fs = require( 'fs-extra' );
const glob = require( 'glob' );
const moment = require( 'moment' );
const axios = require( 'axios' );

const conf=require(`${process.env.dirtown}/conf.json`)

/*
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 ) {
			console.log( "err", retcampain.payload.moreinfo );
			fs.appendFileSync( `${conf.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 = fs.readJsonSync( `${conf.tribes}/tribeids.json` );
	for( let clid in listclient ) {
		console.log( listclient[ clid ] );
		let listaction = glob.sync( `${conf.tribes}/${listclient[clid]}/actions/todo/*.json` );
		for( let action in listaction ) {
			console.log( listaction[ action ] )
			log.nbaction++;
			todo = fs.readJsonSync( listaction[ action ] );
			let passdate = true;
			// currentdate doit etre après la startDate si existe et avant valideuntilDate si existe
			// console.log('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
			// console.log('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' ) );
				//console.log("actiondone"
				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
					fs.outputJsonSync( listaction[ action ].replace( '/todo/', '/done/' ), todo, {
						spaces: 2
					} );
					fs.unlinkSync( listaction[ action ] );
				} else {
					fs.outputJsonSync( 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( `${conf.tribes}/log.txt`, trace, 'utf-8' );
	return "done";
}
module.exports = Contracts;