from django.contrib.auth.models import User
from AdminApp.models import *
from django.conf import settings
from pyfcm import FCMNotification
import os, pdfkit
from Customer.models import *
import pyqrcode, png, os, random, string

def generateqrcode(id_val):
	try:	
		print(id_val)
		
		# from pyqrcode import QRCode
		customerjob_obj = CustomerJob.objects.get(id = id_val)
		st = ''.join([random.choice(string.ascii_letters + string.digits) for n in range(6)])
		filepath = str(settings.BASE_DIR)+'/media/CustomerJobs/'+str(customerjob_obj.id)
		if(os.path.exists(filepath)):
			print('\n\n\n\n')
			print('directory exists')
			pass
		else:
			print('\n\n\n\n')
			print('directory not exists')
			os.umask(0)
			os.makedirs(filepath, mode=0o777)
			# os.mkdir(filepath, mode=0o777)
		
		url = pyqrcode.create(content = 'AWB-' + str(id_val))
		url.png(filepath + '/qrcode.png',scale = 8)
		
		filename = '/media/CustomerJobs/'+str(customerjob_obj.id) + '/qrcode.png'
		customerjob_obj.qrcode = filename
		customerjob_obj.save()
		return('1')
	except Exception as e:
		print(e)

def send_text_message(phone_number, message, message_type):
	try:	
		from telesign.messaging import MessagingClient

		customer_id = str(settings.TELESIGN_CUSTOMER_ID_CLIENT)
		api_key = str(settings.TELESIGN_API_KEY_CLIENT)
		# customer_id = str(settings.TELESIGN_CUSTOMER_ID_OUR1)
		# api_key = str(settings.TELESIGN_API_KEY_OUR1)

		# message_type = "ARN/OTP"
		
		messaging = MessagingClient(customer_id, api_key)
		response = messaging.message(phone_number, message, message_type)
		print(response.json)
		return(True)
	except Exception as e:
		print(e)
		return(False)



def getunreadnotificationcount(user_id):
	user_obj = User.objects.filter(id = user_id).first()
	if user_obj:
		unread_notifications_count = Notifications.objects.filter(user = user_obj, status = 'unread', deleted = False).count()
		return ('success', unread_notifications_count)
	else:
		return ('error', 0)


def sendfcmnotification(fcmtoken_val, app_val, type_val, title_val, message_val):
	try:
		# print(fcmtoken_val)
		server_key = str(settings.FIREBASE_SERVER_KEY)
		print(server_key)
		fcm_token = fcmtoken_val
		message_title = title_val
		message_body = message_val
		data_message = {
					"app": app_val,
					'type': type_val,
					"sendparcel": 'no',
					'title' : title_val,
					"message" : message_val,
				}

		result = FCMNotification(api_key=server_key).notify_single_device(registration_id=fcm_token, message_title=message_title, message_body=message_body, data_message=data_message)
		print(result)
		
	except Exception as error:
		print('error is',error)



def generateparcelpdf(id_val):
	try:	
		print('generateparcelpdf')
		customerjob_obj = CustomerJob.objects.filter(id = id_val).first()
		if customerjob_obj:
			awbnumber = str(10000 + customerjob_obj.id)
			parcellength, parcelheight, parcelwidth, parcelweight = 'N.A.', 'N.A.', 'N.A.', 'N.A.'
			if customerjob_obj.length != '':
				parcellength = customerjob_obj.length
			if customerjob_obj.height != '':
				parcelheight = customerjob_obj.height
			if customerjob_obj.width != '':
				parcelwidth = customerjob_obj.width
			if customerjob_obj.weight != '':
				parcelweight = customerjob_obj.weight
			if customerjob_obj.specialbooking:
				specialbooking = 'Yes'
			else:
				specialbooking = 'No'

			if customerjob_obj.pickupspecialnote:
				pickupspecialnote = customerjob_obj.pickupspecialnote
			else:
				pickupspecialnote = 'N.A.'
			if customerjob_obj.dropoffspecialnote:
				dropoffspecialnote = customerjob_obj.dropoffspecialnote
			else:
				dropoffspecialnote = 'N.A.'


			if customerjob_obj.vehicletype:
				desired_vehicle = customerjob_obj.vehicletype.name
			else:
				desired_vehicle = 'N.A.'

			body = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title>KwickDelivery</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0">
	<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700,900" rel="stylesheet">
	<style>
	th {
	    white-space: nowrap;
	}
</style>
</head>
<body style="margin:0;padding:0;">

	<div style="margin:0; padding:0; width: 100%;">
		<table style="width: 100%;font-family: 'Raleway', Helvetica, Arial, sans-serif;font-size: 16px;color:#666;font-weight: 500;max-width: 860px;margin:auto;border-spacing: 0;">
			<tbody>
				<tr>
					<td style="border-top: 10px solid #39d23a;background: #fff;padding: 20px;">
						<table style="width: 100%;">
							<tr>
								<td style="padding-bottom: 20px;">
									<table  style="width: 100%;">
										<tr>
											<td style="width:55%;background-color: #f5f5f5;padding:30px;">
												<div style="width:100%; text-align: center;">
													<img src='/var/www/html/GoodsDelivery/static/images/logo1.png' style="margin-bottom: 15px;width:130px;"/>
													<h3 style="font-size: 20px;margin:0;color:#242424;">Booking ID :</h3>
													<h4 style="font-size: 16px;margin:0;color:#5b5b5b;">"""+ awbnumber +"""</h4>
												</div>
											</td>
											<td style="width:45%;">
												<div style="width:100%; text-align: center;">
													<img src='/var/www/html/GoodsDelivery"""+ str(customerjob_obj.qrcode.name) + """' style="width:160px;"/>
												</div>
											</td>
										</tr>
									</table>
								</td>
							</tr>
							<tr>
								<td style="padding-bottom: 10px;">
									<table style="width: 100%;">
										<tr>
											<td style="width: 50%; padding-right: 10px;">
												<h3 style="font-size:15px;font-weight: normal;color:#363636;margin:0 0 12px;">SENDER DETAILS</h3>
												<table  style="width: 100%;text-align: left;border:1px solid #d5d5d5;border-bottom:none;border-spacing: 0;">
													<tr>
														<th style="border-bottom: 1px solid #d5d5d5;padding:8px;color:#242424;font-size: 14px;">Sender Name</th>
														<td style="border-bottom: 1px solid #d5d5d5;padding:8px;color:#242424;font-size: 14px;">"""+str(customerjob_obj.sendername)+"""</td>
													</tr>
													<tr>
														<th style="border-bottom: 1px solid #d5d5d5;padding:8px;color:#242424;font-size: 14px;">Sender Contact</th>
														<td style="border-bottom: 1px solid #d5d5d5;padding:8px;color:#242424;font-size: 14px;">"""+str(customerjob_obj.sendercountrycode)+"""-"""+str(customerjob_obj.senderphone)+"""</td>
													</tr>
													<tr>
														<th style="border-bottom: 1px solid #d5d5d5;padding:8px;color:#242424;font-size: 14px;">Pickup Address</th>
														<td style="border-bottom: 1px solid #d5d5d5;padding:8px;color:#242424;font-size: 14px;">"""+str(customerjob_obj.pickupaddress)+"""</td>
													</tr>
													<tr>
														<th style="border-bottom: 1px solid #d5d5d5;padding:8px;color:#242424;font-size: 14px;">Pickup Time Slot</th>
														<td style="border-bottom: 1px solid #d5d5d5;padding:8px;color:#242424;font-size: 14px;">"""+str(customerjob_obj.pickuptimeslot)+"""</td>
													</tr>
												</table>
											</td>



											<td  style="width: 50%; padding-left: 10px;">
												<h3 style="font-size:15px;font-weight: normal;color:#363636; margin-top:-5px;">RECIPIENT DETAILS</h3>
												<table  style="width: 100%;text-align: left;border:1px solid #d5d5d5;border-bottom:none;border-spacing: 0;">
													<tr>
														<th style="border-bottom: 1px solid #d5d5d5;padding:8px;color:#242424;font-size: 14px;">Recipient Name</th>
														<td style="border-bottom: 1px solid #d5d5d5;padding:8px;color:#242424;font-size: 14px;">"""+str(customerjob_obj.recipientname)+"""</td>
													</tr>
													<tr>
														<th style="border-bottom: 1px solid #d5d5d5;padding:8px;color:#242424;font-size: 14px;">Recipient Contact</th>
														<td style="border-bottom: 1px solid #d5d5d5;padding:8px;color:#242424;font-size: 14px;">"""+str(customerjob_obj.recipientcountrycode)+"""-"""+str(customerjob_obj.recipientphone)+"""</td>
													</tr>
													<tr>
														<th style="border-bottom: 1px solid #d5d5d5;padding:8px;color:#242424;font-size: 14px;">Drop Address</th>
														<td style="border-bottom: 1px solid #d5d5d5;padding:8px;color:#242424;font-size: 14px;">"""+str(customerjob_obj.dropoffaddress)+"""</td>
													</tr>
													<tr>
														<th style="border-bottom: 1px solid #d5d5d5;padding:8px;color:#242424;font-size: 14px;">Drop Time Slot</th>
														<td style="border-bottom: 1px solid #d5d5d5;padding:8px;color:#242424;font-size: 14px;">"""+str(customerjob_obj.dropofftimeslot)+"""</td>
													</tr>
												</table>
											</td>
										</tr>
									</table>
								</td>
							</tr>
							<tr>
								<td style="background-color: #f2f1f0;">
									<h3 style="margin:0;text-align: center; font-size: 15px;color:#363636;text-transform: uppercase;padding:8px;">Parcel Details</h3>
												<table  style="width: 100%;text-align: left;border:1px solid #d5d5d5;border-bottom:none;border-spacing: 0;background-color: #fff;">
													<tr>
														<th style="border-bottom: 1px solid #d5d5d5;padding:8px;color:#242424;font-size: 14px;">Parcel Length (CM)</th>
														<td style="border-bottom: 1px solid #d5d5d5;padding:8px;color:#242424;font-size: 14px;">"""+str(parcellength)+"""</td>
													</tr>
													<tr>
														<th style="border-bottom: 1px solid #d5d5d5;padding:8px;color:#242424;font-size: 14px;">Parcel Height (CM)</th>
														<td style="border-bottom: 1px solid #d5d5d5;padding:8px;color:#242424;font-size: 14px;">"""+str(parcelheight)+"""</td>
													</tr>
													<tr>
														<th style="border-bottom: 1px solid #d5d5d5;padding:8px;color:#242424;font-size: 14px;">Parcel Width (CM)</th>
														<td style="border-bottom: 1px solid #d5d5d5;padding:8px;color:#242424;font-size: 14px;">"""+str(parcelwidth)+"""</td>
													</tr>
													<tr>
														<th style="border-bottom: 1px solid #d5d5d5;padding:8px;color:#242424;font-size: 14px;">Weight of Parcel (KG)</th>
														<td style="border-bottom: 1px solid #d5d5d5;padding:8px;color:#242424;font-size: 14px;">"""+str(parcelweight)+"""</td>
													</tr>
													<tr>
														<th style="border-bottom: 1px solid #d5d5d5;padding:8px;color:#242424;font-size: 14px;">Parcel Type</th>
														<td style="border-bottom: 1px solid #d5d5d5;padding:8px;color:#242424;font-size: 14px;">"""+str(customerjob_obj.parceltype)+"""</td>
													</tr>
													<tr>
														<th style="border-bottom: 1px solid #d5d5d5;padding:8px;color:#242424;font-size: 14px;">Pickup Special Note: </th>
														<td style="border-bottom: 1px solid #d5d5d5;padding:8px;color:#242424;font-size: 14px;">"""+str(pickupspecialnote)+"""</td>
													</tr>
													<tr>
														<th style="border-bottom: 1px solid #d5d5d5;padding:8px;color:#242424;font-size: 14px;">Drop Special Note: </th>
														<td style="border-bottom: 1px solid #d5d5d5;padding:8px;color:#242424;font-size: 14px;">"""+str(dropoffspecialnote)+"""</td>
													</tr>
													<tr>
														<th style="border-bottom: 1px solid #d5d5d5;padding:8px;color:#242424;font-size: 14px;">Special Booking</th>
														<td style="border-bottom: 1px solid #d5d5d5;padding:8px;color:#242424;font-size: 14px;">"""+str(specialbooking)+"""</td>
													</tr>
													<tr>
														<th style="border-bottom: 1px solid #d5d5d5;padding:8px;color:#242424;font-size: 14px;">Desired Vehicle</th>
														<td style="border-bottom: 1px solid #d5d5d5;padding:8px;color:#242424;font-size: 14px;">"""+str(desired_vehicle)+"""</td>
													</tr>
													
												</table>
								</td>
							</tr>
							<tr>
								<td style="background-color: #fff;padding:5px;"></td>
							</tr>
							<tr>
								<td style="background-color: #f2f1f0;height:38px;">
									<h3 style="margin:0;text-align: center; font-size: 13px;color:#858484;padding:8px;">www.kwickdelivery.co.uk</h3>
								</td>
							</tr>
						</table>
					</td>
				</tr>
			</tbody>
		</table>
	</div>	
</body>
</html>

			 	"""

			# print(body)
			print('before awb pdf generation')
			filepath = str(settings.BASE_DIR)+'/media/CustomerJobs/'+str(customerjob_obj.id)
			if(os.path.exists(filepath)):
				pass
			else:
				# os.makedirs(filepath, mode=0o777)
				os.mkdir(filepath, mode=0o777)


			# payment_receipt_html = open(filepath+'/awb.html',"w", encoding='utf-8')
			payment_receipt_html = open(filepath+'/awb.html',"w")
			payment_receipt_html.write(body)
			print('000000')
			pdfkit.from_file(filepath+'/awb.html', filepath+'/awb.pdf')
			print('111111')
			filename = '/media/CustomerJobs/'+str(customerjob_obj.id) + '/awb.pdf'
			# print(filename)
			print('222222')
			customerjob_obj.parcelpdf = filename
			customerjob_obj.save()
			print('3333333')
			return (True)
	except Exception as e:
		print(e)
		filename = '/media/CustomerJobs/'+str(customerjob_obj.id) + '/awb.pdf'
		customerjob_obj.parcelpdf = filename
		customerjob_obj.save()
		return (False)