#!/usr/bin/env python
# -*- coding: utf-8 -*-
from .models import *
import datetime
import sense_core as sd
from . import msg_base, utils
import time
from .share_interface import Share
from .check_db_exist import check_db_exist

sd.log_init_config(root_path=sd.config('log_path'))


class MonitMessageSender(object):
	
	def _send_err_message(self, module, title = '日志出现错误', phone_list=None):
		module_config = {}
		db = check_db_exist()
		if not db:
			phone_list = phone_list
		else:
			module_config = Share.get_module_config(module)
			phone_list = Share.get_contact_list(module_config['user'], 'phone')
		send_res = self._send_message(module, title, phone_list)
		suc_phone = []
		fail_phone = []
		if not send_res:
			sd.log_info('[*] Module ' + module + ' errors message has been sent failed.')
		else:
			sd.log_info(send_res)
			suc_phone, fail_phone = self._check_send_result(send_res)
			suc_list = []
			fail_list = []
			if fail_phone and len(fail_phone) != 0:
				suc_list, fail_list = self._resend_msg(fail_phone, title)
			suc_phone.extend(suc_list)
			fail_phone = fail_list
		if not db:
			sd.log_info('The success send phone is:{}, the failed send phone is:{}'.format(suc_phone, fail_phone))
		else:
			self._update_msg_db(module, title, str(module_config['user']), suc_phone, fail_phone)

	def _send_message(self, module, title, phone_list=None):
		msg_res = self._send_msg_detail(phone_list, module, title)
		return msg_res
	
	def _check_send_result(self, send_res):
		suc_phone, fail_phone = [], []
		if send_res['code'] == 'OK':
			suc_phone = send_res['addr']
		elif send_res['code'] == 'Failed':
			suc_phone = send_res['suc_list']
			fail_phone = send_res['failed_list']
		return suc_phone, fail_phone
	
	def _update_msg_db(self, module_name, content, uid, success_phone, fail_phone):
		msg_send_log = MsgSendLog()
		session = msg_send_log.get_session()
		_now = datetime.datetime.now()
		if success_phone and len(success_phone) != 0:
			for item in success_phone:
				bulk_object = MsgSendLog(module=module_name, content=content, uids=uid, phone=item,
										 status='success', time=_now)
				session.add(bulk_object)
		if fail_phone and len(fail_phone) != 0:
			for item in fail_phone:
				bulk_object = MsgSendLog(module=module_name, content=content, uids=uid, phone=item,
										 status='failed', time=_now)
				session.add(bulk_object)
		try:
			session.commit()
		except Exception as e:
			sd.log_warn('update err message db occur error:{0}'.format(e))
		finally:
			msg_send_log.close_session(session)
	
	def _send_msg_detail(self, phone_list, module, err_title):
		failed_list = []
		suc_list = []
		template_code = sd.config('aliyun_sms', 'msg_template')
		if not phone_list or len(phone_list) == 0:
			sd.log_info('The receiver phone is empty')
			return None
		for phone in phone_list:
			if not phone:
				sd.log_info('[ALIYUN] ' + str(phone) + ' is not a phone number!')
				continue
			res = eval(
				msg_base.send_sms(phone, template_code, {'code': -9, 'message': module + err_title}).decode())
			res_suc, res_failed = self._parse_msg_res(res, phone)
			suc_list.extend(res_suc)
			failed_list.extend(res_failed)
			time.sleep(2)
		if len(failed_list) == 0:
			res = utils.build_dic(code='OK', flag='message', addr=phone_list, content=template_code)
			sd.log_info('message send successful!!!')
		else:
			res = utils.build_dic(code='Failed', flag='message', content=template_code, failed_list=failed_list,
								  suc_list=suc_list)
			sd.log_info(res)
		return res
	
	def _parse_msg_res(self, res, phone):
		failed_list = []
		suc_list = []
		if not isinstance(res, dict) or 'Code' not in res:
			return None
		if res['Code'] == 'OK':
			suc_list.append(phone)
		else:
			failed_list.append(phone)
		return suc_list, failed_list
	
	def _resend_msg(self, fail_phone, title):
		success_list = []
		fail_list = fail_phone
		if fail_list and len(fail_list) != 0:
			i = 1
			while i < 3:
				sd.log_info('message send fail, the failed phone is {}, now try {} resend'.format(fail_list, i))
				msg_res = self._send_msg_detail(fail_list, title)
				if msg_res['code'] == 'OK':
					success_list.extend(fail_list)
					fail_list = []
					break
				elif msg_res['code'] == 'Failed':
					fail_list = msg_res['failed_list']
					success_list.extend(msg_res['suc_list'])
				i += 1
		return success_list, fail_list




