#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
 
#include "./include/db_adaptor.h"

#define MAX_ROWS	100
#define MAX_FILEDS	16
#define MAX_FIELD_LEN 256

_db_cfg  db_cfg;

static char network_name[128]={"AGrandtech Lab"};
static char sender_addr[128];
static int   reciever_num=0;
static char receiver_addr[16][128];

static int	  query_rows = 0;
static char query_result[MAX_ROWS][MAX_FILEDS][MAX_FIELD_LEN];

static int	  to_be_handled_rows = 0;
static char to_be_handled_result[MAX_ROWS][MAX_FILEDS][MAX_FIELD_LEN];

/*-------------------------------------------------*/

int dbc_connect_host(u8 db_index)
{
	char host_info[128];
 	_db_link *db_ptr=NULL;
	unsigned int timeout = 1;
	MYSQL*tmp_conn = NULL;
	
	db_ptr = &db_cfg.db_link[db_index];	
	if(db_ptr->enable == 0 || db_ptr->conn_status == 1)
		return 0;
		
	if ((db_ptr->db_conn  = mysql_init(NULL)) == NULL) {
		return -1;
	}
	
	mysql_options(db_ptr->db_conn, MYSQL_OPT_CONNECT_TIMEOUT, (const char *)&timeout);
		
//	sprintf(host_info,"%s", db_ptr->str_host_ip);
	sprintf(host_info,"%s", "127.0.0.1");

//	tmp_conn = mysql_real_connect(db_ptr->db_conn, host_info, db_ptr->client_name, db_ptr->client_pwd, db_ptr->db_name, 0, NULL, 0 );
	tmp_conn = mysql_real_connect(db_ptr->db_conn, host_info, "root", "rootaa", "OMC_PUB", 0, NULL, 0 );

	if(tmp_conn != NULL)
	{
		db_ptr->conn_status = 1;
		db_cfg.total_active_links ++;
	}
	else
	{
		db_ptr->conn_status = 0;
		mysql_close(db_ptr->db_conn);
		return -1;		
	}
	
	if(db_cfg.total_active_links == 1)
	{
		db_cfg.current_working_link_id = db_index;
	}
	
	
	return 1;	
}

MYSQL 	*dba_get_working_conn()
{
	MYSQL 	*db_conn = NULL;
	u8 	index = db_cfg.current_working_link_id;
	
	if(db_cfg.total_active_links == 0)
		return NULL;
	if( index < MAX_DB_CONN)
	{
		db_conn = db_cfg.db_link[index].db_conn;
	}
	
	return db_conn;
}


int dba_db_sql_execute(const char *sql, int max_rows, int max_fields)
{
	int 			rc;
	int           	i, rows, fields;	
	u16 			length;
	MYSQL 		*db_conn;
	MYSQL_RES 	*res_ptr;
	MYSQL_ROW    row;

	if(sql == NULL)
		return 0;
		
	db_conn = dba_get_working_conn();
	if(db_conn == NULL)
		return 0;

	
	length = strlen(sql);
	rc = mysql_real_query(db_conn, sql, length);
	if(rc != 0)
	{
	    //release_mysql_connection(db_conn);
		return 0;
	}
	if(max_rows == 0)//update not query
		return 1;
	
	res_ptr = mysql_store_result(db_conn);
	if(res_ptr == NULL)
	{
		return 0;
	}

	rows = mysql_num_rows(res_ptr);
	if(rows == 0)
	{
		mysql_free_result(res_ptr);  	
		return 0;
	}
	
	rows = 0;
	fields = mysql_num_fields(res_ptr);
	if(fields > max_fields)
		fields = max_fields;

	while ((row = mysql_fetch_row(res_ptr))) 
	{
		for (i = 0; i < fields; i++)
		{
			if(row[i] == NULL)
			{
				query_result[rows][i][0] = 0;
				if(max_rows == 1)
				{
					goto empty;
				}
			}
			else
				strcpy(query_result[rows][i], row[i]);
		}
		if(rows++ >= max_rows)
			break;
	}

empty:	
	mysql_free_result(res_ptr);  	

	return rows;//fields;	
}

void scan_alarm()
{
	int rows = 0;
	int i;
	char sql[256];

	sprintf(sql, "select sysTypeNo, compCode, alarmCode, alarmTime from sysAlarmLog where clearMode=0 and alertCheck=0 LIMIT %d", MAX_ROWS);

	query_rows = dba_db_sql_execute(sql, MAX_ROWS, 4);
	if(query_rows>0)
	{
		to_be_handled_rows = query_rows;
		memcpy(to_be_handled_result, query_result, sizeof(query_result));
		
		for(i=0; i<query_rows; i++)
		{			
			sprintf(sql, "update sysAlarmLog set alertCheck=1 where sysTypeNo=%s and compCode=%s and alarmCode=%s",
				query_result[i][0], 
				query_result[i][1],				
				query_result[i][2]);
			dba_db_sql_execute(sql, 0,0);
		}
	}
}

void send_alarm()
{
	int i;
	int rows=0;
	char sql[256];
	char subject[128], alarm_content[256];
	char tmp_buf[128];
	char receiver_str[1024],command[1024];

	if(reciever_num>0)
		sprintf(receiver_str, "%s", receiver_addr[0]);
	
	for(i=1;i<reciever_num;i++)
	{
		sprintf(tmp_buf, ", %s", receiver_addr[i]);
		strcat(receiver_str, tmp_buf);
	}
	
	for(i=0; i<to_be_handled_rows; i++)
	{
		sprintf(sql, "select level_1, alarmDesc_2 from sysAlarmConf where sysTypeNo=%s and compCode=%s and alarmCode=%s and SendAlert=1", 
			to_be_handled_result[i][0], 
			to_be_handled_result[i][1],				
			to_be_handled_result[i][2]);

		rows = dba_db_sql_execute(sql, 1,2);
		if(rows > 0)
		{
			if(0)
			{
				sprintf(subject, "%s, alarm of %s", network_name,  query_result[0][0]);
				sprintf(alarm_content, "%s", query_result[0][1]);
				smtp_send_alert(sender_addr,
							reciever_num,
							receiver_addr,
							subject,
							alarm_content);
			}
			else
			{
				int ret=0;
				sprintf(command,"echo \"%s\" | mutt -s \"%s, alarm of %s\" %s", query_result[0][1], network_name,  query_result[0][0], receiver_str);
				ret = system(command);
				printf("%s, ret=%d\n", command, ret);
			}
		}
	}

	to_be_handled_rows = 0;

}

void read_alarm_email_config()
{
	int rows, i;
	char sql[256];
	
	reciever_num = 0;

	sprintf(sql, "select pubVarValue from omcPubVarConf where pubVarName='fieldName'");
	rows = dba_db_sql_execute(sql, 1, 1);
	if(rows > 0)
	{
		strcpy(network_name, query_result[0][0]);
	}	

	sprintf(sql, "select pubVarValue from omcPubVarConf where pubVarName='AlertSender'");
	rows = dba_db_sql_execute(sql, 1, 1);
	if(rows > 0)
	{
		strcpy(sender_addr, query_result[0][0]);
	}	

	for(i=0; i<5; i++)
	{
		sprintf(sql, "select pubVarValue from omcPubVarConf where pubVarName='AlertReceiver%d'", i);
		rows = dba_db_sql_execute(sql, 1, 1);
		if(rows > 0 && strlen(query_result[0][0]) > 3)
		{
			strcpy(receiver_addr[reciever_num], query_result[0][0]);
			reciever_num ++;
			
		}	
	}
	
}

int dba_conn_thread(void *param)
{
	register u32 check_conn_timer = 0;

	db_cfg.current_working_link_id = INVALID_DB_LINK_ID;

	db_cfg.db_link[0].enable = 1;
	
	dbc_connect_host(0);
	
	while(1)
	{
		if(check_conn_timer % 10 == 0)//10s
		{
			dbc_connect_host(0);
			read_alarm_email_config();
			//dbc_connect_host(1);
		}
		check_conn_timer ++;	

		scan_alarm();
		if(to_be_handled_rows>0)
			send_alarm();
		
		sleep(1);
	}
	
	return 1;
}
