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

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"}

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 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':

		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) VALUES ('"+str(customer_number1)+"',5,now()) 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())
		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) \
					VALUES (now(),'"+str(customer_name)+"','"+str(customer_number1)+"','"+str(product_path)+"',"+str(customer_id)+",1)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 = "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! For any query please write to us at feedback@bigcity.in . Team BigCity"
			saveMessageWhatsapp(customer_number,entry,message_pro)
		
		
		return str(5)
	else:
		print("Get method not called")

def saveMessageSms(mobile,msgSubject,message_content):
    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
		a = saveMessageWhatsapp(customer_number,entry,message_pro)
		return str(1)


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