#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This is the Live version of AISPms

@author: pmctaggart
"""
###############################################################################
###########################  AISP Initialisations  ############################
###############################################################################

import sys, os
from datetime import datetime, timedelta

sys.path.append(os.path.dirname(os.path.realpath(__file__)) + '/')              # Auto path append - SWITCH ON

#sys.path.append('/Users/pmctaggart/Work/AISP/Python2/Working/Test_Version_v1/')   # Manual path append - SWITCH OFF

import AISP_mod_Staging as AISP_mod 

###############################################################################
###########################  Flask Initialisations  ###########################
###############################################################################

from flask import Flask, request, jsonify, Response
app = Flask(__name__)
app.config["DEBUG"] = True

# uuid = '0fa18fb2-639d-4101-9ba7-9af790963afe'
# uuid = 'test_365'

###############################################################################
##############################  Main - Sign-up  ###############################
###############################################################################

@app.route('/customer', methods=['GET', 'POST'])
def get_URL():
    uuid = request.args['id']

    #### - Create lead
    lead_dict = AISP_mod.fetch_leads(uuid)                                     # Sets up customer_id with saltedge

    #### - Create lead session and get URL
    from_date = (datetime.today() - timedelta(days=364)).strftime('%Y-%m-%d')  #Confirm what this is
    session_dict = AISP_mod.create_lead_session(customer_id = str(lead_dict['data']['customer_id']),
                                                           from_date=from_date,
                                                           period_days = 90)

    redirect_URL = session_dict['data']['redirect_url']
    customer_id  = str(lead_dict['data']['customer_id'])
    
    #### - Count connections
    connections_url = "https://www.saltedge.com/api/partners/v1/connections?customer_id=" + str(	customer_id)
    connection_count = len(AISP_mod.get_response(connections_url)['data'])
    
    #### - Move lead (customer) to database - (UUID, customer ID, status)
    status = "session_created"    
    status_query = AISP_mod.get_status_full_update(uuid,  customer_id,  status, connection_count)
    AISP_mod.aisp_query(status_query)
    
    #### - Add URL return event to callback table
    created_at = datetime.today().strftime('%Y-%m-%d %H:%M:%S')
    callback_query = AISP_mod.get_callback_update("session_created",
                                                       "uuid:" + str(uuid),
                                                       customer_id,
                                                       "none",
                                                       "none",
                                                       created_at)
    AISP_mod.aisp_query(callback_query)
    
    status_url = 'https://api.staging.mymoneyjar.com/internal-api/1.0/aisp/' + str(uuid)                     ###### NEW ###### 
    payload = '{"status":"session_created"}'                                                                 ###### NEW ######
    AISP_mod.patch_response_api(status_url, payload)                                                         ###### NEW ######

    return(str(redirect_URL))

##############################################################################################################

@app.route('/customer/required', methods=['GET','POST'])
def get_required():
    uuid = request.args['id']
    
    ### - Update status table
    require_query_status   = AISP_mod.get_status_update(uuid, "", "required", -1)
    AISP_mod.aisp_query(require_query_status) 
    
    status_url = 'https://api.staging.mymoneyjar.com/internal-api/1.0/aisp/' + str(uuid)                     ###### NEW ######
    payload = '{"status":"required"}'                                                                        ###### NEW ######
    AISP_mod.patch_response_api(status_url, payload)                                                         ###### NEW ######
    
    return (str("Required : " + str(uuid)))

##############################################################################################################

@app.route('/customer/status', methods=['GET','POST'])
def get_status():
    uuid = request.args['id']
    
    ### - Get status 
    status_query   = AISP_mod.get_status_pull(uuid, "status")
    status = AISP_mod.aisp_query_one(status_query)
    
    status_url = 'https://api.staging.mymoneyjar.com/internal-api/1.0/aisp/' + str(uuid)                    ###### NEW ######
    payload = '{"status":"' + str(status) + '"}'                                                            ###### NEW ######
    AISP_mod.patch_response_api(status_url, payload)                                                        ###### NEW ######
    
    return (str("Status : " + str(status)))

##############################################################################################################

@app.route('/customer/reject', methods=['GET','POST'])
def reject_user():
    uuid = request.args['id']
    
    ### - Update status table
    reject_query_status   = AISP_mod.get_status_update(uuid, "", "reject", -1)
    AISP_mod.aisp_query(reject_query_status)                      

    ### - Update callback table
    created_at = datetime.today().strftime('%Y-%m-%d %H:%M:%S')
    reject_query_callback = AISP_mod.get_callback_update("reject",
                                                              "uuid:" + str(uuid),
                                                              "none",
                                                              "none",
                                                              "none",
                                                              created_at)
    AISP_mod.aisp_query(reject_query_callback)

    status_url = 'https://api.staging.mymoneyjar.com/internal-api/1.0/aisp/' + str(uuid)            ###### NEW ######
    payload = '{"status":"rejected"}'                                                               ###### NEW ######
    AISP_mod.patch_response_api(status_url, payload)                                                ###### NEW ######

    return (str("Rejected : " + str(uuid)))

##############################################################################################################

@app.route('/customer/acknowledged', methods=['GET','POST'])
def get_acknowledgement():
    uuid = request.args['id']
    
    ## Previous Connections
    connections_query   = AISP_mod.get_status_pull(uuid, "*")
    connections = AISP_mod.aisp_query_all(connections_query)

    try:
        customer_id = connections[0][1]
        status_url = 'https://api.staging.mymoneyjar.com/internal-api/1.0/aisp/' + str(uuid)          ###### NEW - MOVE? ######
        payload = '{"status":"acknowledged"}'                                                         ###### NEW - MOVE? ######
        AISP_mod.patch_response_api(status_url, payload)                                              ###### NEW - MOVE? ######        
    except:
        status_url = 'https://api.staging.mymoneyjar.com/internal-api/1.0/aisp/' + str(uuid)          ###### NEW - MOVE? ######        
        payload = '{"status":"unknown user"}'                                                         ###### NEW - MOVE? ######
        AISP_mod.patch_response_api(status_url, payload)                                              ###### NEW - MOVE? ######
        return Response("Could not find user in database", status=500, mimetype='application/json')   ### CHECK FUNCTIONALITY ###
   
    # count saltedge connections
    connections_url = "https://www.saltedge.com/api/partners/v1/connections?customer_id=" + str(customer_id)
    conn_saltedge_count = len(AISP_mod.get_response(connections_url)['data'])

    # count database connections  
    conn_database_count = int(connections[0][3])
#    conn_database_count = int(AISP_mod.aisp_query_one("Select connections from aispDB.user_status where customer_id = '" + str(customer_id) + "';"))

    # Change in connections count
    connection_change = conn_saltedge_count - conn_database_count
    
    if connection_change == 1:
        AISP_mod.aisp_query_safe("Update aispDB.user_status set status = 'acknowledged', connections = \
                                 '" + str(conn_saltedge_count) + "' where customer_id = '" + str(customer_id) + "';")
#        return "Success"
    elif connection_change == 0:
        pass
#        return Response("User has not added an account", status=500, mimetype='application/json')
    else:
        AISP_mod.aisp_query_safe("Update aispDB.user_status set connections = '" + str(conn_saltedge_count) + "' \
                                where customer_id = '" + str(customer_id) + "';")
#        return Response("Unknown issue, connections changed from " + str(conn_database_count) + " to " + str(conn_saltedge_count), status=500, mimetype='application/json')


###############################################################################
##############################  Main - Other  ###############################
###############################################################################    
    
@app.route('/help', methods=['GET', 'POST'])
def poll_help():
    return "\
    ========================== <br/> \
    === MyMoneyJar - AISP help: === <br/> \
    ========================== <br/> \
    <br/> \
    To use polling microservice: <br/> \
    <br/> \
    Staging - https://aisp.staging.mymoneyjar.com/ <br/> \
    <br/> \
    Live    - https://aisp.mymoneyjar.com/ <br/> \
    <br/> \
    GET URL: <br/> \
    /customer/{id} <br/> \
    <br/> \
    CHECK STATUS: <br/> \
    /customer/status/{id} <br/> \
    <br/> \
    SET STATUS - required: <br/> \
    /customer/required/{id} <br/> \
    <br/> \
    SET STATUS - reject: <br/> \
    /customer/reject/{id} <br/> \
    <br/> \
    SET STATUS - acknowledged: <br/> \
    /customer/acknowledged/{id} <br/> \
    <br/> \
    TEST MS Active<br/> \
        /test <br/> \
    "

# @app.route('/test/<event>/<uuid>', methods=['GET', 'POST'])
@app.route('/test', methods=['GET', 'POST'])
def test_response():
    import datetime
    return "AISP MS currently active : " + str(datetime.datetime.now()) 
#    return "Event: " + str(event) + ", UUID: " + str(uuid)
    
###############################################################################
##############################  Main - Consent  ###############################
###############################################################################    

@app.route('/refresh', methods=['GET','POST'])
def consent_date():
    consent = AISP_mod.fetch_consent(customer_id)
    

@app.route('/refresh', methods=['GET','POST'])
def refresh_user():
    
    refresh_URL = fetch_refresh(customer_id, connection_id)
    return refresh_URL

@app.route('/reconnect', methods=['GET','POST'])
def reconnect_user():
    
    reconnect_URL = fetch_refresh(customer_id, connection_id)
    return reconnect_URL

@app.route('/customer/refresh_acknowledged', methods=['GET','POST'])
def get_refresh_acknowledgement():
    uuid = request.args['id']


@app.route('/customer/reconnect_acknowledged', methods=['GET','POST'])
def get_reconnect_acknowledgement():
    uuid = request.args['id'] 

###############################################################################
##################################  Other  ####################################
###############################################################################



if __name__ == "__main__":
    app.run(host='0.0.0.0')
    
    
