const fs = require( 'fs-extra' );
const path = require( 'path' );
const formidable = require( 'formidable' );
const jsonfile = require( 'jsonfile' );
const mustache = require( 'mustache' );
const config = require( '../tribes/townconf.js' );

/*
model A SUPPRIMER !!!!!!!!!!!!!!!!!!!!!!
les functions d'upload de file et de droits d'accès doivent être gérer dans Tribes

*/
const UploadFiles = {};
UploadFiles.get = function ( filename, header ) {
	// check file exist
	const file = `${config.tribes}/${header.xworkon}/${filename}`;
	// logger.info('fichier demande ', file);
	if( !fs.existsSync( file ) ) {
		// logger.info('le fichier demande n existe pas ', file);
		return {
			status: 404,
			payload: { info: [ 'fileUnknown' ], model: 'UploadFiles' }
		};
	} else {
		logger.info( 'envoie le fichier ', file );
		return {
			status: 200,
			payload: { info: [ 'fileknown' ], model: 'UploadFiles', file: file }
		};
	}
};
UploadFiles.addjson = function ( data, header ) {
	/*
	Le header = {X-WorkOn:"",destinationfile:"", filename:""}
	Le body = {jsonp:{},callback:function to launch after download,'code':'mot cle pour verifier que le fichier est à garder'}
	*/
	// logger.info(req.body.jsonp);
	try {
		jsonfile.writeFileSync( header.destinationfile + '/' + header.filename, data.jsonp );
		if( data.callback ) {
			const execCB = require( `${config.mainDir}/models/tribeid/${
        header.xworkon
      }` );
			execCB[ data.callback ]();
		}
		return {
			status: 200,
			payload: {
				info: [ 'wellUpload' ],
				model: 'UploadFiles',
				render: {
					destination: header.destinationfile,
					filename: header.filename
				}
			}
		};
	} catch ( err ) {
		logger.info( 'Impossible de sauvegarder le fichier, A COMPRENDRE', err );
		return {
			status: 503,
			payload: { info: [ 'savingError' ], model: 'UploadFiles' }
		};
	}
};
UploadFiles.add = function ( req, header ) {
	const form = new formidable.IncomingForm();
	logger.info( 'req.headers', req.headers );
	logger.info( 'req.params', req.params );
	logger.info( 'req.query', req.query );
	logger.info( 'req.body', req.body );
	let destinationfile = `${config.tribes}/${header.xworkon}/${
    header.destinationfile
  }`;
	form.parse( req, function ( err, fields, files ) {
		logger.info( 'files', files.file.path );
		logger.info( 'fields', fields );
		const oldpath = files.file.path;
		destinationfile += '/' + files.file.name;
		logger.info( 'oldpath', oldpath );
		logger.info( 'destinationfile', destinationfile );
		fs.copyFile( oldpath, destinationfile, function ( err ) {
			if( err ) {
				logger.info( err );
				return {
					status: 500,
					payload: { info: [ 'savingError' ], model: 'UploadFiles' }
				};
			} else {
				logger.info( 'passe' );
				fs.unlink( oldpath );
				return {
					status: 200,
					payload: {
						info: [ 'wellUpload' ],
						model: 'UploadFiles',
						render: {
							destination: destinationfile
						}
					}
				};
			}
		} );
	} );
};
UploadFiles.updateEvent = function ( domainId, eventId, event ) {
	//  checkAndCreateNeededDirectories(domainId);
	const eventsFile = `${config.tribes}/${domainId}/actions/events/events.json`;
	if( !fs.existsSync( eventsFile ) ) {
		jsonfile.writeFileSync( eventsFile, {} );
		return { status: 404, payload: 'You have not any events.' };
	}
	const events = jsonfile.readFileSync( eventsFile );
	if( !events.hasOwnProperty( eventId ) ) {
		return {
			status: 404,
			payload: 'The event you are trying to update does not exist.'
		};
	}
	events[ eventId ] = {
		eventName: event.eventName,
		eventDate: event.eventDate,
		eventDescription: event.eventDescription
	};
	jsonfile.writeFileSync( eventsFile, events, { spaces: 2 } );
	return {
		status: 200,
		payload: events
	};
};
UploadFiles.deleteEvent = function ( domainId, eventId ) {
	// checkAndCreateNeededDirectories(domainId);
	const eventsFile = `${config.tribes}/${domainId}/actions/events/events.json`;
	if( !fs.existsSync( eventsFile ) ) {
		jsonfile.writeFileSync( eventsFile, {} );
		return { status: 404, payload: 'You have not any events.' };
	}
	const events = jsonfile.readFileSync( eventsFile );
	if( events.hasOwnProperty( eventId ) ) {
		delete events[ eventId ];
		jsonfile.writeFileSync( eventsFile, events, { spaces: 2 } );
		return {
			status: 200,
			payload: events
		};
	} else {
		return {
			status: 404,
			payload: 'The event you are trying to delete does not exist.'
		};
	}
};
module.exports = UploadFiles;
