let errorHandler = {},
    logger = require('../../logger'),
	semusiConfig = require('./../config'),
	semusiMail = require('./../parts/mgmt/mail.js'),
	fs = require('fs'),
	path = require('path'),
	moment = require('moment');

(function(errorHandler){
	errorHandler.writeError = function(error){
		if(error){
			let errorData = '\r\n';
			errorData += moment().format('DD-MM-YYYY H:m:s')+"    at "+semusiConfig.cdnUrl;
			errorData += ' \r\n';
			errorData += JSON.stringify(error);
			errorData += ' \r\n';
			errorData += '========================================================';
			let filePath = path.join(__dirname,"../../errorHandler.log");
			fs.appendFile(filePath, errorData, function(error, res){
				if(error){
					logger.error(`error occure while write error handling log :: ${error}`);
				}
			})
		}
	}

	errorHandler.sendError = function(error){
		if(error){
			// write error log into file
			errorHandler.writeError(error);
			// send mail error to mail
			if(semusiConfig.errorMails){
				let errorData = moment().format('DD-MM-YYYY');
				errorData = ' <br />'
				errorData = JSON.stringify(error);
				semusiConfig.errorMails.forEach(function(email){
					let message = {
			            to:email,
			            subject:'AppICE system error',
			            html:'Hi,<br/><br/>' +
			                ' error : '+errorData+'<br/><br/>' +
			                'Appice Team,<br/>' +
			                'Server: <a href="'+semusiConfig.cdnUrl+'" target="_blank">'+semusiConfig.cdnUrl+'</a>'
			        };

			        semusiMail.sendMail(message);
				});
			}
		}
	}
	
	errorHandler.sendLog= function(log, subject){
        if(log){
            // write error log into file
            errorHandler.writeError(log);
            // send mail error to mail
            if(semusiConfig.errorMails){
                let errorData = moment().format('DD-MM-YYYY');
                errorData = ' <br />'
                errorData = JSON.stringify(log);
                semusiConfig.errorMails.forEach(function(email){
                    let message = {
                        to:email,
                        subject:subject,
                        html:'Hi,<br/><br/>' +
                        ' Log : '+errorData+'<br/><br/>' +
                        'Appice Team,<br/>' +
                        'Server: <a href="'+semusiConfig.cdnUrl+'" target="_blank">'+semusiConfig.cdnUrl+'</a>'
                    };

                    semusiMail.sendMail(message);
                });
            }
        }
    }

}(errorHandler));

module.exports = errorHandler;