from flask import Flask, jsonify, render_template, url_for, request, redirect, json, make_response, redirect
from datetime import datetime, timedelta


import pymysql, os, math, requests, uuid

import sendgrid
from sendgrid.helpers.mail import * 


# File imports
from routes.v1 import app
from routes.v1 import db
# from routes import celery

from databases.volunteers import Volunteers, Gender, Country
from databases.programs import Programs, Images
from databases.applications import Applications
from .variables import *
from werkzeug.utils import secure_filename

from simple_salesforce import Salesforce

def close(self):
	self.session.close()


@app.route('/volunteer/payment', methods=['POST'])
def getPaymentAmount():
	application_uuid = request.json['application_uuid'] # The Application ID
	phone_number = request.json['phone_number']

	volunteer = db.session.query(Applications).filter_by(public_id=application_uuid).first()
	if volunteer.payment_status == str(1):
		return jsonify({'message' : 'The user has already paid'}), 412
		
	if volunteer:
		if volunteer.currency == "KES" or volunteer.currency == "USD":
			# get how much to pay 
			cost,  = db.session.query(Programs.price).filter_by(public_id=volunteer.program_id).first()
			if int(cost) <= 70000:
				try:
					if int(cost) <= 1:
						return jsonify({'message' : 'Amount is less than 1'}), 412
						
					payload = {
						'amount' : cost,
						'payment_to' : "Volunteer",
						'reference' : application_uuid,
						'phone_number' : phone_number
					}
					requests.post('https://{}:5019/checkout'.format(app.config['SERVER']), json=payload)
					responseObject = {
						'message' : "Kindly check your mobile for payment"
					}
					return make_response(jsonify(responseObject)), 200
				except Exception as err:
					responseObject = {
						'message' : str(err)
					}
					return make_response(jsonify(responseObject)), 500
			else:
				responseObject = {
					'message' : 'The amount exceeds KES 70,000'
				}
				return make_response(jsonify(responseObject)), 412
		else:
			cost,  = db.session.query(Programs.price).filter_by(public_id=volunteer.program_id).first()
			if int(cost)*100 <= 70000:
				responseObject = {
					'message' : 'Kindly check your mobile for payment'
				}
				return make_response(jsonify(responseObject)), 200
			else:
				responseObject = {
					'message' : 'The amount exceeds KES 70,000'
				}
				return make_response(jsonify(responseObject)), 412
	# res = add.apply_async()
	else:
		responseObject = {
			'message' : 'Could not find the member'
		}
		return make_response(jsonify(responseObject)), 412