from flask import Flask, jsonify, abort, request, json
from flask_cors import CORS,cross_origin
from flask_restful import Api, Resource, reqparse
from sqlalchemy import desc, func
from sqlalchemy.sql import text
from sqlalchemy.orm.exc import NoResultFound
from db.models import db, CustomerDataModel, MessageModel, VoucherModel, SentimentAnalysisDataModel
import json
import datetime
import time
import requests
import re
import gzip
from waitress import serve
from io import BytesIO
import urllib.request
from skimage import io
import uuid
import cv2
import argparse
from enum import Enum
import os
from PIL import Image, ImageDraw
import re
import requests
from pytz import timezone
import pytz, datetime
import numpy as np
from PIL import Image
from scipy.spatial import distance
import base64
import urllib3
from uuid import uuid4
import requests
import sys
import traceback
import urllib


app = Flask(__name__)
cors = CORS(app, resources={r"/*": {"origins": "*"}})
app.config['SECRET_KEY'] = 'abcdefghijklmnllpqrst'
app.config['CORS_HEADERS'] = 'Content-Type'
app.config['Access-Control-Allow-Origin'] = '*'
app.config['Access-Control-Request-Headers'] = '*'
app.config['Access-Control-Allow-Credentials'] = True
app.config['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS, PUT'
parser = reqparse.RequestParser()
app.config.from_pyfile('conf/psql-config.py')
db.init_app(app)
headers         = {"api-key":"A714af0a570cf003da623225d34558f78"}

class UrlShortenTinyurl:
	URL = "http://tinyurl.com/api-create.php"

	def shorten(self, url_long):
		try:
			url = self.URL + "?" \
				+ urllib.parse.urlencode({"url": url_long})
			res = requests.get(url)
			print("STATUS CODE:", res.status_code)
			print("   LONG URL:", url_long)
			print("  SHORT URL:", res.text)
			return res.text
		except Exception as e:
			raise


def saveMessageWhatsapp(customer_number,entry,message_pro):
	ins_sql             = "INSERT INTO itc_user_message_log(mobile_number,outgoing_message,created_date) \
						   VALUES ('"+str(customer_number)+"','"+str(message_pro)+"',now())"
	#sel_res				=  db.engine.execute(ins_sql)
	url_send 			= 'https://global.kaleyra.com/api/v4/?method=wa&api_key=Ae0b471f12259cb4f610621aa13299002&body={ "to": '+str(customer_number)+', "type": "text", "preview_url": false, "callback": "http://example.com/callback?", "text": { "message": '+str(json.dumps(message_pro))+' }}&from=917338373383'
	print(url_send)
	r 					=  requests.post(url=url_send)
	print(r.text)
	
	return str(1)

def shortenUrl(customer_number):
							
	rand_token = uuid4()
	rand_token = str(rand_token)
	rand_token = rand_token.replace('-','')
	http = urllib3.PoolManager()
	url_long ="http://staging10.bigcityvoucher.co.in/index.php?deeplink_token="+str(rand_token)+"&mobile="+str(customer_number)
	r = http.request('GET',url_long)
	print(r.status)

	try:
		obj = UrlShortenTinyurl()
		msg = obj.shorten(url_long)	
		return msg
	except Exception as e:
		traceback.print_exc()

def getAsianTimeStamp():

	current_time_zone      = datetime.datetime.now(pytz.timezone('Asia/Calcutta'))
	current_time = current_time_zone.replace(tzinfo=None)
	return current_time

@cross_origin()
@app.route('/api/v1/budspacewhtsbill',methods=['POST','GET'])
def voiceUploadKalyera():

	print("cametoapi")
	if request.method =='GET':
		try:
			request_data      	= request.args['message']
			json_data         	= json.loads(request_data)
			tn_status               = 0
			for row in json_data:
				customer_number = row['from']
				url   		    = row['url']
				customer_name	= row['profile']['name']
				type_sms 		= row['type']


			print(url)
			current_time    = getAsianTimeStamp()
			today_date      = current_time.strftime("%Y-%m-%d")

			customer_number1 = customer_number[2:]

			sel_sql = "SELECT id FROM customers where mobile = '"+str(customer_number1)+"' "
			sel_res = db.engine.execute(sel_sql).fetchone()
			if(sel_res):
				customer_id = sel_res['id']
			else:
				ins_sql = "INSERT into customers (mobile,is_social_login,createdon,source_from) VALUES ('"+str(customer_number1)+"',5,now(),5) RETURNING id"
				ins_res = db.engine.execute(ins_sql).fetchone()
				customer_id = ins_res['id']

			a_string = url
			new_string = a_string.replace(" ", "%20")
			image = io.imread(new_string)
			unique_filename = str(uuid.uuid4())

			sel_res = "SELECT id,whtsapp_invoice_msg FROM customer_invoices WHERE customer_number = '"+str(customer_number1)+"' AND whatsapp_invoice_flag = 0 ORDER BY id desc"
			whatsapp_res = db.engine.execute(sel_res).fetchone()
			print("Sel  res")
			if(whatsapp_res):
				entry	   = whatsapp_res['id']
				whtsapp_invoice_msg = whatsapp_res['whtsapp_invoice_msg']
				if(whtsapp_invoice_msg == 0):
					print("2nd image")
					img = cv2.imwrite("/var/www/staging10.bigcityvoucher.co.in/api1/web/uploads/customerinvoices/"+str(unique_filename)+".jpg", image)
					detect_file = os.path.abspath("/var/www/staging10.bigcityvoucher.co.in/api1/web/uploads/customerinvoices/"+str(unique_filename)+".jpg")
					product_path = "http://api1.staging10.bigcityvoucher.co.in/uploads/customerinvoices/"+str(unique_filename)+".jpg"
					ins_sql    = "INSERT into customer_invoice_transactions (customer_invoice_id,invoice_path) VALUES ("+str(entry)+",'"+str(product_path)+"')"
					whatsapp_res = db.engine.execute(ins_sql)
					sel_sql = "select count(*) AS count from customer_invoice_transactions where customer_invoice_id = "+str(entry)
					sel_res  = db.engine.execute(sel_sql).fetchone()
					if(sel_res):
						total_count = sel_res['count']
						if(total_count < 3):
							message_pro = "Success!Is the bill too long? We've got you covered.Reply with 1 if you have more than one picture of the same invoice. Reply with 2 if you don't. Team BigCity"
							saveMessageWhatsapp(customer_number,entry,message_pro)
							upd_sql = "UPDATE customer_invoices set whtsapp_invoice_msg = 1 where id = "+str(entry)
							whatsapp_res = db.engine.execute(upd_sql)
						else:
							upd_sql = "UPDATE customer_invoices set whatsapp_invoice_flag = 1,invoice_status = 0 where id = "+str(entry)
							whatsapp_res = db.engine.execute(upd_sql)
							entry = 0
							tiny_url = shortenUrl(customer_number1)
							message_pro = "Thank you! Your request to avail Happy Hour offer on the BudSpace app is now in process. Once your bill is verified, your points balance will be updated. click to explore "+str(tiny_url)+". Till then, Enjoy your Bud! For any query please write to us at feedback@bigcity.in. Team BigCity"
							saveMessageWhatsapp(customer_number,entry,message_pro)
				else:
					message_pro = "Invalid entry.Reply with 1 if you have more than one picture of the same invoice. Reply with 2 if you don't. Team BigCity"
					saveMessageWhatsapp(customer_number,entry,message_pro)
			else:
				print("1st image")
				img = cv2.imwrite("/var/www/staging10.bigcityvoucher.co.in/api1/web/uploads/customerinvoices/"+str(unique_filename)+".jpg", image)
				detect_file = os.path.abspath("/var/www/staging10.bigcityvoucher.co.in/api1/web/uploads/customerinvoices/"+str(unique_filename)+".jpg")

				product_path = "http://api1.staging10.bigcityvoucher.co.in/uploads/customerinvoices/"+str(unique_filename)+".jpg"
				ins_sql = "INSERT INTO customer_invoices(created_date,customer_name,customer_number,invoice_path,customer_id,whatsapp_flag,whatsapp_invoice_flag,whtsapp_invoice_msg,invoice_status) \
							VALUES (now(),'"+str(customer_name)+"','"+str(customer_number1)+"','"+str(product_path)+"',"+str(customer_id)+",1,0,1,10)RETURNING id"
				
				whatsapp_res = db.engine.execute(ins_sql).fetchone()
				if(whatsapp_res):
					entry  = whatsapp_res['id']

					ins_sql    = "INSERT into customer_invoice_transactions (customer_invoice_id,invoice_path) VALUES ("+str(entry)+",'"+str(product_path)+"')"
					whatsapp_res = db.engine.execute(ins_sql)

					message_pro = "Success!Is the bill too long? We've got you covered.Reply with 1 if you have more than one picture of the same invoice. Reply with 2 if you don't. Team BigCity"
					saveMessageWhatsapp(customer_number,entry,message_pro)
	
		except:
			for row in json_data:
				
				mobile_number = row['from'].strip()               
				message_content = row['text']['body']
				customer_name   = row['profile']['name']
				customer_number1 = mobile_number[2:]
				entry = 0
				sel_sql = "SELECT id FROM customer_invoices WHERE customer_number = '"+str(customer_number1)+"' AND whatsapp_invoice_flag = 0 ORDER BY id desc"
				print(sel_sql)
				whatsapp_res = db.engine.execute(sel_sql).fetchone()
				if(whatsapp_res):
					invoice_id = whatsapp_res['id']
					print(invoice_id)
					if(message_content == '1' and len(message_content) == 1):
						upd_sql = "UPDATE customer_invoices set whtsapp_invoice_msg = 0 where id = "+str(invoice_id)
						whatsapp_res = db.engine.execute(upd_sql)
						message_pro = "Please share the next image."
						saveMessageWhatsapp(customer_number,entry,message_pro)
					
					elif(message_content == '2' and len(message_content) == 1 ):
						upd_sql = "UPDATE customer_invoices set whatsapp_invoice_flag = 1,invoice_status = 0 where id = "+str(invoice_id)
						whatsapp_res = db.engine.execute(upd_sql)
						entry = 0
						tiny_url = shortenUrl(customer_number1)
						message_pro = "Thank you! Your request to avail Happy Hour offer on the BudSpace app is now in process. Once your bill is verified, your points balance will be updated. Till then, Enjoy your Bud! Click here to explore more "+str(tiny_url)+". For any query please write to us at feedback@bigcity.in. Team BigCity"
						saveMessageWhatsapp(customer_number,entry,message_pro)
					else:
						message_pro = "Invalid entry. Reply with 1 if you have more than one picture of the same invoice. Reply with 2 if you don't. Team BigCity"
						saveMessageWhatsapp(customer_number,entry,message_pro)
				else:
					pass		
		return str(5)
	else:
		print("Get method not called")

def saveMessageSms(mobile,message_content,template_id):
	msgSubject = 'offer sms'
	insert_message = "INSERT INTO messages(createdon, fromid, toid, sub, body, msgtype, status, campaign_id) VALUES (now(),'BIGCITY','"+str(mobile)+"','"+str(msgSubject)+"','"+str(message_content)+"',2,0,12) "
	db.engine.execute(insert_message)
	return str(1)

@cross_origin()
@app.route('/api/v1/sendWhatsapp',methods=['POST','GET'])
def sendWhatsapp():
	if request.method == 'POST' or request.method == 'GET':
		customer_number        = request.json['to']
		customer_number        = "91"+str(customer_number)
		message_pro            = request.json['message']
		entry                  = 0
		message_whatsapp       = request.json['message_whatsapp']
		msg_check              = request.json['msg_check']
		tiny_url 			   = shortenUrl(customer_number)
		message_pro            = message_pro.replace('budepllaliga_tinyurl',tiny_url)
		if(message_whatsapp == 1):
			a = saveMessageWhatsapp(customer_number,entry,message_pro)
		else:
			if(msg_check == 1):
				template_id = 0
				a = saveMessageSms(customer_number,message_pro,template_id)
			elif(msg_check == 2):
				template_id = 1
				a = saveMessageSms(customer_number,message_pro,template_id)
			else:
				pass
		return str(1)


if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0',port=5001)
