var express = require('express')
var app = express()
var nodemailer = require('nodemailer');
var mail_target = ''
var port = '3000'
var request = require("request")
var os = require('os');
var interfaces = os.networkInterfaces();
var addresses = [];
for (var k in interfaces) {
    for (var k2 in interfaces[k]) {
        var address = interfaces[k][k2];
        if (address.family === 'IPv4' && !address.internal) {
            addresses.push(address.address);
        }
    }
}
ip=addresses[0]
console.log('Почтовая рассылка запущена')


var gray='#95a5a6'
var l_gray='#ecf0f1'
var d_blue='#34495e'
var blue='#2980b9'
var red='#c0392b'
var green='#27ae60'
var yellow='#f39c12'
var d_red='#96281B'
var white='#fff'
var purple='#9b59b6'
var html_style='<style>'+
						'td {padding: 5px 5px 5px 5px}'+
						'table {table-layout:fixed;word-wrap: break-word;-webkit-font-smoothing: antialiased;border-collapse:collapse;}'+
					'</style>'
var table_header= '<tr style="background:'+red+';color:'+white+'">'+
							'<td style="width:20px"></td>'+
							'<td>Название операции</td>'+
							'<td style="width:150px">Пользователь</td>'+
							'<td style="width:150px">Время выполнения</td>'+
							'<td style="width:150px">Время окончания</td>'+
						'</tr>'
var last_mail = ''
var last_id=0
var transporter = nodemailer.createTransport('smtp://exchange.diasoft.ru:25');
var CronJob = require('cron').CronJob;
new CronJob('00 */1 * * * *', function() {
	console.log('Запрос ушел')
	request({
		url: 'http://localhost:'+port+'/settings/mail_send_get_data?line_id='+last_id,
		json: true,
		headers: {
		    'Authorization': new Buffer("sensor:sensor").toString('base64')
		}
	}, function (error, response, body) {
		
		if (!error && response.statusCode === 200) {
			console.log(body)
	   	for (i=0;i<body.mailing.length;i++){
				mail_body=''
				rule=body.mailing
				mail_target=''
	   		for (mails=0;mails < rule[i].mails.length;mails++){
	   			if (rule[i].mails.length-1 == mails){
	   				mail_target+=rule[i].mails[mails]
	   			}else{
	   				mail_target+=rule[i].mails[mails]+','
	   			}
	   		}
				mail_body+=html_style
				mail_body+='	<table style="width:100%;color:'+d_blue+';border:2px solid '+red+';font-size:14px">'
				mail_body+='<tr>'+
									'<td style="width:20px"></td>'+
									'<td colspan="4" style="font-size:18px" align="right"><b>Операции, которые превысили KPI по времени выполнения</b></td>'+
								'</tr>'
				mail_body+=table_header
	   		for (data=0;data<rule[i].data.length;data++){
					if (data % 2){color=white}else{color=l_gray}
					if (rule[i].data[data].status < rule[i].data[data].kpi){status_color=yellow}else{status_color=red}
					mail_body+=		'<tr style="background:'+color+'">'+
											'<td><div style="width:20px;height:20px;border-radius:10px;background:'+status_color+'"></div></td>'+
											'<td>'+rule[i].data[data].oper_name+'</td>'+
											'<td>'+rule[i].data[data].login_name+'</td>'+
											'<td>'+second_to_hour_converter(rule[i].data[data].duration)+'</td>'+
											'<td>'+rule[i].data[data].end_time.split('T')[0]+' '+rule[i].data[data].end_time.split('T')[1].split('.')[0]+'</td>'+
										'</tr>'
	   		}
				mail_body+=		'</table>'
			  	var mailOptions = {
				    from: '"Diasoft Sensor" sensor@diasoft.ru', 
				    to: mail_target, 
				    subject: 'Diasoft Sensor оповещение',
				    html: mail_body
			  	};
				if (rule[i].data.length > 0){
					transporter.sendMail(mailOptions, function(error, info){
						if(error){
				      	return console.log(error);
						}
						last_mail='Письмо улетело - '+new Date()
						console.log('Письмо улетело - '+new Date());
					});	
				}
	   	} 
		last_id=body.last_id
		}else{
			console.log(error)
			console.log(response.statusCode)
		}
 	})
  }, null, true, 'Europe/Moscow');
  
app.get('/mail_check', function(req, res) {
  	res.jsonp({status: "ok"})
})
app.get('/mail_stop', function(req, res) {
	process.exit()
})
app.listen(3010)




function second_to_hour_converter(seconds){
		if (parseInt(seconds*1000) == 0){
			return 'меньше 1 мс.'
		}
		if(parseInt(seconds) > 3){
			seconds=parseInt(seconds)
			hour=Math.floor(seconds/3600)
			min=Math.floor((seconds-hour*3600)/60)
			sec=seconds-hour*3600-min*60
			if (hour+min+sec == 0){
				return 'меньше 1 сек.'
			}
			if (hour < 10){
				hour="0"+hour
			}
			if (min < 10){
				min="0"+min
			}
			if (sec < 10){
				sec="0"+sec
			}
		
			output_time=hour+'ч. '+min+'м. '+sec+'с.'
			return output_time
		}else{
			ms=seconds*1000
			output_time=parseInt(ms)+'мс.'
			return output_time
		}
}


