# -*- coding: utf-8 -*-

from odoo import api, fields, models
import urllib2
import urllib
import ssl
import unicodedata
from odoo.exceptions import RedirectWarning, UserError, ValidationError
from odoo import models, fields, api, _
from xml.dom.minidom import Node
import xml.dom.minidom
from odoo import tools
import re
from datetime import datetime
# main mako-like expression pattern
EXPRESSION_PATTERN = re.compile('(\$\{.+?\})')

ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

class SMS(models.Model):
	_name = 'sms.sms'
	_description = "SMS by CVMovel"

	number = fields.Char(string='Phone')
	number_t = fields.Char(string='Phone')
	message = fields.Text(string='Message', required=True)
	template = fields.Many2one('mail.template', string='Tempate SMS')
	phonecall_id = fields.Many2one('lams.phonecall', string='Phone Call ID', readonly=True)
	datetime= fields.Datetime(string='Assigned', readonly=True, index=True)
	state= fields.Char(string='State', readonly=True)


	@api.model
	def default_get(self, fields):
		res = super(SMS, self).default_get(fields)
		move = self.env['lams.phonecall'].browse(self._context.get('active_ids'))
		number = []
		n = []
		for i in move:
			if i.attendee_mobile:
				number.append(str(i.attendee_mobile))
		if 'number' in fields:
			res.update({'number': number})
		#print("NUMBER DEFAULT GET: ",number)
		return res

	@api.onchange('template')
	def onchange_temp(self):
		if self.template:
			self.number_t = self.template.number
			self.message = self.template.content

	@api.multi
	def sendSMS(self):
		self.action_sendSMS(self.number, self.message)
		return self.env['warning'].info(title='Sucesso', message="Os SMS foram enviados com sucesso!!!")
	@api.one
	def action_sendSMS(self, number, message):
		msg=[]
		if not number:
			# self.template.state = 'notsend'
			raise ValidationError(_('No Mobile\'s information for send SMS'))
		active_ids = self._context.get('active_ids')
		#print("ACTIVE IDS: "+str(active_ids))
		part_obj = self.env['lams.phonecall']
		for res_id in part_obj.browse(active_ids):
			self.Send(res_id.attendee_mobile,message,res_id.date,res_id.id)
			msg.append({"number":res_id.attendee_mobile,"message":message})
		if msg:
			print("RETURN SUCESS")
			#print("MESSAGE: "+str(msg))
			return True
		return False

	@api.one
	def Send(self,number,message,date,phonecall_id):

		#print("MESSAGE FIRST LOG: "+message)
		#print("NUMBER FIRST LOG: "+number)
		phonecall = self.env['lams.phonecall'].browse(phonecall_id)
		nip = phonecall.project_id.nip
		message = message + ' NIP: ' + nip
		original_message = message
		message = unicodedata.normalize('NFKD', message).encode('ASCII', 'ignore').decode('ASCII')


		if number[0] == "+":
			number = urllib.urlencode({'number': number})
			number1 = number.split('=')
			number = number1[1]
			number = number.replace(' ', '')
		elif number[0] == "0":
			raise ValidationError(_(
				'The phone number must be formated like this: + followed by country operator followed by the numbers without characters. e.g. : +3265698745'))
		message = message.decode('UTF-8')
		message = urllib.urlencode({'message': message})
		#print("MESSAGE LOG: "+message)
		msg = message.split('=')
		message = msg[1]
		sender = unicode('Cadastro Predial')
		sender = unicodedata.normalize('NFKD', sender).encode('ASCII', 'ignore').decode('ASCII')
		sender = sender.decode('UTF-8')
		sender = urllib.urlencode({'sender': sender})
		#print("SENDER LOG: "+sender)

		#url="https://cvmensagens.cvmovel.cv/GwHTTPin/sendtext?UID=3046&PW=EPEhUe9BNhuR7j%2FBBl4U0g%3D%3D&O="+sender+"&M="+message+"&N="+number
		url="https://cvmensagens.cvmovel.cv/GwHTTPin/sendtext?UID=3046&PW=EPEhUe9BNhuR7j%2FBBl4U0g%3D%3D&O=Cadastro&M="+message+"&N="+number
		the_page ="999999"
		try:
			handle =urllib2.urlopen(url, context=ctx)
			#print("HANDLE LOG: " + str(handle))
			the_page = handle.read()
		
		except:
			raise ValidationError(_('The SMS Service is Down'))
			
		str_the_page = str(the_page)
		str_number = str(number)
		#print("THE PAGE LOG: " + str(the_page))
		#print("NUMBER: " + str(number))
		codes = str_the_page.split(",")
		numbers = number.split(",")
		success_numbers=[] 
		unsuccess_numbers=[] 
		for i,num in enumerate(codes):
			if num == '01':
				success_numbers.append(numbers[i])
			elif num == '92':
				unsuccess_numbers.append(numbers[i])
		#print "SUCCESS NUMBERS:::: ",success_numbers
		#print "UNSUCCESS NUMBERS:::: ",unsuccess_numbers
		final_message=''
		if len(success_numbers) > 0:
			success="Com sucesso: " + ",".join(str(x) for x in success_numbers) + "<br>"
			final_message = final_message + success
		if len(unsuccess_numbers) > 0:
			unsuccess="Sem sucesso: " + ",".join(str(x) for x in unsuccess_numbers) + "<br>"
			final_message = final_message + unsuccess
		final_message = final_message + original_message
		if the_page:
			self.history(str(the_page))
			msg_record_name=str(date)
			self.env['mail.message'].create({'body': final_message, 'record_name': msg_record_name, 'date': datetime.now(),'model':'lams.phonecall','message_type':'comment','website_published':True,'res_id':phonecall_id,'subtype_id':2})
			phonecall.write({'sms_sent':True})

	@api.one
	def history(self, result):
		active_ids = self._context.get('active_ids')
		#print "ACTIVE IDS::::::::::::",active_ids
		part_obj = self.env['lams.phonecall']
		msg_obj = self.env['sms.sms']
		part=part_obj.browse(active_ids)
		#print("PART OBJECT: "+str(part))
		sms = []
		for res_id in part:
			msg = msg_obj.create({'number': res_id.attendee_mobile, 'message': self.message,
								  'template': self.template and self.template.id or False,
								  'phonecall_id': res_id.id, 'state': result, 'datetime': datetime.now()})
			sms.append(msg)
			msg_body=self.message
			msg_res_id=res_id.id
			#print "ID PHONECALL::::::::::::",res_id.id
			#print "PHONECALL IDS::::::::::::",phonecalls_ids
				#print "VAI CRIAR A MENSAGEM::::::::::::::::::::"
		print ("SMS SENT: "+str(sms))


	def getText(self, nodelist):
		rc = []
		for node in nodelist:
			if node.nodeType == node.TEXT_NODE:
				rc.append(node.data)
		return ''.join(rc)

