from flask import make_response, request, current_app, Flask, jsonify
from functools import update_wrapper
import json
import wrapper as wp
import ela_user_account as eua
import prj_common as pc
from six import string_types
from datetime import timedelta
import Ela_Spacy as ls
import user_message_mgt as um
import user_session as us

import partners as pa
import prj_common as mycommon
import ela_index_bdd_classes as ela_index_class
import class_mgt as cm
import Dev_api_functions as dev_function
from flask_cors import CORS, cross_origin
import time
from OpenSSL import SSL
from flask import redirect
from flask import Flask, render_template, request, redirect, url_for
import articles_avis as aa
import GlobalVariable as MYSY_GV
import youtubes_analyse as YTA
import test_perso as TP
import ela_factures_mgt as invoice
import product_service as PS
import ela_factures_mgt as factures
import statistics as Stat

app = Flask(__name__)
cors = CORS(app, resources={r"/foo": {"origins": "*"}})
app.config['CORS_HEADERS'] = 'Content-Type'
app.config['UPLOAD_FOLDER'] = MYSY_GV.upload_folder
app.env = "Production"

@app.before_request
def before_request():
    if mycommon.check_source_ipv4(str(request.remote_addr)) is False:
        return "Security check : '" + request.remote_addr + "' is not autorized", 404


def crossdomain(origin=None, methods=None, headers=None, max_age=21600,
                attach_to_all=True, automatic_options=True):
    """Decorator function that allows crossdomain requests.
      Courtesy of
      https://blog.skyred.fi/articles/better-crossdomain-snippet-for-flask.html
    """
    if methods is not None:
        methods = ', '.join(sorted(x.upper() for x in methods))
    # use str instead of basestring if using Python 3.x
    if headers is not None and not isinstance(headers, str):
        headers = ', '.join(x.upper() for x in headers)
    # use str instead of basestring if using Python 3.x
    if not isinstance(origin, str):
        origin = ', '.join(origin)
    if isinstance(max_age, timedelta):
        max_age = max_age.total_seconds()

    def get_methods():
        """ Determines which methods are allowed
        """
        if methods is not None:
            return methods

        options_resp = current_app.make_default_options_response()
        return options_resp.headers['allow']

    def decorator(f):
        """The decorator function
        """
        def wrapped_function(*args, **kwargs):
            """Caries out the actual cross domain code
            """
            if automatic_options and request.method == 'OPTIONS':
                resp = current_app.make_default_options_response()
            else:
                resp = make_response(f(*args, **kwargs))
            if not attach_to_all and request.method != 'OPTIONS':
                return resp

            h = resp.headers
            h['Access-Control-Allow-Origin'] = origin
            h['Access-Control-Allow-Methods'] = get_methods()
            h['Access-Control-Max-Age'] = str(max_age)
            h['Access-Control-Allow-Credentials'] = 'true'
            h['Access-Control-Allow-Headers'] = \
                "Origin, X-Requested-With, Content-Type, Accept, Authorization"
            if headers is not None:
                h['Access-Control-Allow-Headers'] = headers
            return resp

        f.provide_automatic_options = False
        return update_wrapper(wrapped_function, f)
    return decorator

@app.after_request
def after_request(response):
  response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
  response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')

  return response



'''
cette API gere le login et la creation du token
'''
@app.route('/myclass/api/login/', methods=['POST','GET'])
@crossdomain(origin='*')
def login():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, retval = us.login(payload)
    return jsonify(status=status, message=retval)



'''
cette API recupere les objectifs d'un utilisateur

La clé est l'adresse email.
si le nom de la formation est fourni, alors l'api va retourner la formation donnée
'''
@app.route('/myclass/api/get_user_objectif/', methods=['POST','GET'])
@crossdomain(origin='*')
def get_user_objectif():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, retval = eua.get_user_objectif(payload)
    return jsonify(status=status, message=retval)


'''
Cette API desactive un objectif.
les clés sont : 
- adresse email
- nom de l'objectif

'''
@app.route('/myclass/api/desable_user_objectif/', methods=['POST'])
@crossdomain(origin='*')
def desable_user_objectif():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, retval = eua.desable_user_objectif(payload)
    return jsonify(status=status, message=retval)



'''
Cette API recupere l'historique de recherche
d'un utilisateur
'''
@app.route('/myclass/api/get_user_recherche_history/', methods=['POST','POST'])
@crossdomain(origin='*')
def get_user_recherche_history():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, retval = eua.get_user_recherche_history(payload)
    return jsonify(status=status, message=retval)


'''
Cette API ajoute un objectif à un utilisateur
la clé est l'adresse email
'''
@app.route('/myclass/api/add_update_user_objectif/', methods=['POST'])
@crossdomain(origin='*')
def add_update_user_objectif():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, retval = eua.add_update_user_objectif(payload)  
    return jsonify(status=status, message=retval)



'''
Cette Api retourne les info d'un user accout identifié par 
son adresse email.
'''
@app.route('/myclass/api/get_user_account/', methods=['POST','GET'])
@crossdomain(origin='*')
def get_user_account():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ", payload)
    result, message = eua.get_user_account(payload)
    return jsonify(status=result, message=message)


'''
Cette API créer un compte utilisateur et declenche l'envoi de l'email de notification
'''
@app.route('/myclass/api/add_user_account/', methods=['POST'])
@crossdomain(origin='*')
def add_user_account():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    result, message = eua.add_user_account(payload)
    return jsonify(status=result, message=message)


'''
Cette API valide une inscription d'un user
'''
@app.route('/myclass/api/valide_user_account/<value>', methods=['GET','POST'])
@crossdomain(origin='*')
def valide_user_account(value):

    print(" ### validation du compte = ",value)
    status, retval = eua.valide_user_account(value)

    url = ""
    if( status ):
        if (MYSY_GV.MYSY_ENV == "PROD"):
            url = 'https://www.mysy-training.com/mysy-account-activated/'
        elif (MYSY_GV.MYSY_ENV == "DEV"):
            url = 'http://localhost:3009/mysy-account-activated/'
    else:
        if (MYSY_GV.MYSY_ENV == "PROD"):
            url = 'https://www.mysy-training.com/erreur'

        elif (MYSY_GV.MYSY_ENV == "DEV"):
            url = 'http://localhost:3009/erreur/'

    return  redirect(url)


'''
Cette api met à jour un compte utilisateur
'''
@app.route('/myclass/api/update_user_account/', methods=['POST','GET'])
@crossdomain(origin='*')
def update_user_account():
    payload = request.form.to_dict()
    print(" ### payload = ", payload)
    status, retval = eua.update_user_account(payload)
    return jsonify(status=status, message=retval)


@app.route('/myclass/api/create_class/', methods=['POST','GET'])
@crossdomain(origin='*')
def create_class():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, retval = cm.add_class(payload)
    return jsonify(status=status, message=retval)



'''
Cette api recupete et affiche une formation.
la clé d'une formation est le code externe, 
mais pour que l'api fonctionne, il faut lui fournir

- le token du partenaire
'''
@app.route('/myclass/api/get_class/', methods=['POST','GET'])
@crossdomain(origin='*')
def get_class():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",str(payload)+"  IP requester = "+str(request.remote_addr))

    status, retval = cm.get_class(payload)
    return jsonify(status=status, message=retval)


'''
Cette api recupete la formation d'un partenaire donnée
elle est appelée exclusivement en mode connecté

- le token du partenaire
'''
@app.route('/myclass/api/get_partner_class/', methods=['POST','GET'])
@crossdomain(origin='*')
def get_partner_class():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",str(payload)+"  IP requester = "+str(request.remote_addr))
    status, retval = cm.get_partner_class(payload)
    return jsonify(status=status, message=retval)


"""
Cette API retourne le code externe de toutes les formations
d'un partenaire 
"""
@app.route('/myclass/api/get_partner_class_external_code/', methods=['POST','GET'])
@crossdomain(origin='*')
def get_partner_class_external_code():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",str(payload)+"  IP requester = "+str(request.remote_addr))
    status, retval = cm.get_partner_class_external_code(payload)
    return jsonify(status=status, message=retval)




@app.route('/myclass/api/update_class/', methods=['POST'])
@crossdomain(origin='*')
def update_class():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, retval = cm.update_class(payload)
    return jsonify(status=status, message=retval)


'''
deverrouillage  d'une formation  - unlock training

'''
@app.route('/myclass/api/unlock_class/', methods=['POST'])
@crossdomain(origin='*')
def unlock_class():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, retval = cm.unlock_class(payload)
    return jsonify(status=status, message=retval)

'''
Verrouillage  d'une formation  - lock training
'''
@app.route('/myclass/api/lock_class/', methods=['POST'])
@crossdomain(origin='*')
def lock_class():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, retval = cm.lock_class(payload)
    return jsonify(status=status, message=retval)


'''
API de Depublication d'une formation
'''
@app.route('/myclass/api/unpublish_class/', methods=['POST'])
@crossdomain(origin='*')
def unpublish_class():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, retval = cm.unpublish_class(payload)
    return jsonify(status=status, message=retval)


'''
API de Publication d'une formation
'''
@app.route('/myclass/api/pusblish_class/', methods=['POST'])
@crossdomain(origin='*')
def pusblish_class():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, retval = cm.pusblish_class(payload)
    return jsonify(status=status, message=retval)



'''
Desactivé une formation  - disable training

'''
@app.route('/myclass/api/disable_class/', methods=['POST'])
@crossdomain(origin='*')
def disable_class():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, retval = cm.disable_class(payload)
    return jsonify(status=status, message=retval)

'''
Reactivation d'une formation  - enable training
'''
@app.route('/myclass/api/enable_class/', methods=['POST'])
@crossdomain(origin='*')
def enable_class():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, retval = cm.enable_class(payload)
    return jsonify(status=status, message=retval)




'''
Cette api retourne les formations dont "attribut"="valeur"
'''
@app.route('/myclass/api/get_class_by_name/<attribut>,<value>', methods=['GET','POST'])
@crossdomain(origin='*')
def get_all_class_by_attribut(attribut, value):
    result = wp.get_all_class_by_attribut(attribut, value)
    if result:
        #print(" in main result =  ", result)
        return jsonify(result)

    return jsonify(status="False")


'''
Cette api retourne les formations dont "attribut" IN (list_valeurs)
list_valeurs = val1,val2,val3,...,valn
'''
@app.route('/myclass/api/get_class_by_list_attr/<attribut>;<list_values>', methods=['GET'])
@crossdomain(origin='*')
def get_class_by_list_attr(attribut, list_values):
    print(" ### attribut = "+attribut)

    result = wp.get_class_by_list_attr(attribut, list_values)
    if result:
        #print(" in main result =  ", result)
        return jsonify(result)
    return jsonify(status="False")


'''
fonction actuellement utilisé sur le front : 
Cette fonction "get_recherche_gle_class"  prend en argument une phrase et
retourne les formations associées
'''
@app.route('/myclass/api/get_recherche_gle_class/<sentence>', methods=['GET'])
@crossdomain(origin='*')
def get_recherche_gle_class(sentence):

    result = wp.get_recherche_gle_class(sentence)
    if result:
        #print(" in main result =  ", result)
        return jsonify(result)
    return jsonify(status="False")


'''
Fonction utilisée pour la recherche simple d'un texte.
sans utilisation de critère ni de tag

'''
@app.route('/myclass/api/recherche_text_simple/', methods=['GET','POST'])
@crossdomain(origin='*')
def recherche_text_simple():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    #print(" ### payload = ", payload)
    status, result = wp.recherche_text_simple(payload)
    return jsonify(status=status, message=result)



# recherche globale
'''
fonction NON utilisée sur le front : 
Cette fonction fait une recherche globale en prenant une chaine de caractère  - not use on front
'''
@app.route('/myclass/api/get_class_global_search/<search_string>', methods=['GET','POST'])
@crossdomain(origin='*')
def get_class_global_search(search_string):
    result = cm.get_class_global_search(search_string)
    if result:
        #print(" in main result =  ", result)
        return jsonify(result)

    return jsonify(status="False")


@app.route('/myclass/api/get_all_class/', methods=['GET','POST'])
@crossdomain(origin='*')
def get_all_class():
    if mycommon.check_source_ipv4(str(request.remote_addr)) is False :
        return  jsonify(status="False", message="Security check : "+request.remote_addr+"' is not autorized")

    payload = request.form.to_dict()
    status, result = wp.get_all_class(payload)
    print(" ### payload = ", payload)
    response =  jsonify(status=status, message=result)
    response.headers.add("Access-Control-Allow-Origin", "*")
    response.headers.add("Access-Control-Allow-Headers", "*")
    response.headers.add("Access-Control-Allow-Methods", "*")
    return response



@app.route('/myclass/api/update_class_by_attribut/<objId>,<attribut>,<value>', methods=['GET','POST'])
def update_class_by_attribut(objId, attribut, value):
    print(" update_class_by_attribut ")
    result = wp.update_class_by_attribut(objId, attribut, value)
    if result:
        print(" in main result =  ", result)
        return jsonify(result)

    return jsonify(status="False")

# this function update all fields of class.
# First : we retrieve all field of class and display it.
# Second : the user update some fields but all fields will be returned for update
# it means all field are stored in :
# payload = request.form.to_dict()
@app.route('/myclass/api/update_class_by_id/<id>', methods=['GET','POST'])
def update_class_by_id(id):
    payload = request.form.to_dict()
    print("on va modifier l'id (fourni en input) : ", id)
    for key, value in payload.items():
        print(key," : ", value)

    result = wp.update_class(payload)
    #result = "1"
    if result:
        return jsonify(status='True', message='Class updated')
    return jsonify(status='False')


'''
Cette API créer un compte patenaire / client  et declenche l'envoi de l'email de notification
La clé est reste l'adresse email du partenaire (pas du contact du partenaire)
'''
@app.route('/myclass/api/add_partner_account/', methods=['POST','GET'])
@crossdomain(origin='*')
def add_partner_account():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, retval = pa.add_partner_account(payload)
    return jsonify(status=status, message=retval)



'''
Cette API valide une inscription d'un partenaire
'''
@app.route('/myclass/api/valide_partnair_account/<value>', methods=['GET','POST'])
@crossdomain(origin='*')
def valide_partnair_account(value):

    print(" ### validation du compte = ",value)
    result, token = pa.valide_partnair_account(value)

    if (result):
        if (MYSY_GV.MYSY_ENV == "PROD"):
            url = 'https://www.mysy-training.com/PartnerLogin0/'
        elif (MYSY_GV.MYSY_ENV == "DEV"):
            url = 'http://localhost:3009/PartnerLogin0'
    else:
        if (MYSY_GV.MYSY_ENV == "PROD"):
            url = 'https://www.mysy-training.com/erreur'
        elif (MYSY_GV.MYSY_ENV == "DEV"):
            url = 'https://www.mysy-training.com/erreur'

    return redirect(url)



'''
Cette fonction modifie/MAJ un partenaire
'''
@app.route('/myclass/api/update_partner_account/', methods=['POST','GET'])
@crossdomain(origin='*')
def update_partner_account():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, retval = pa.update_partner_account(payload)
    return jsonify(status=status, message=retval)



'''
Partenair SECURITY : Cette API  modifie/MAJ le mail du  partenaire
'''
@app.route('/myclass/api/update_partner_main_mail/', methods=['POST','GET'])
@crossdomain(origin='*')
def update_partner_main_mail():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, retval = pa.update_partner_main_mail(payload)
    return jsonify(status=status, message=retval)




'''
Partenair SECURITY : Cette API  modifie/MAJ le password du  partenaire
'''
@app.route('/myclass/api/update_partner_pwd/', methods=['POST','GET'])
@crossdomain(origin='*')
def update_partner_pwd():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, retval = pa.update_partner_pwd(payload)
    return jsonify(status=status, message=retval)




'''
Cette fonction recupere les données d'un partenaire

'''
@app.route('/myclass/api/get_partner_account/', methods=['POST','GET'])
@crossdomain(origin='*')
def get_partner_account():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, retval = pa.get_partner_account(payload)
    return jsonify(status=status, message=retval)



'''
Cette API index la base donnée.
La fonction "ela_index_all_classes" va aller chercher chaque cours dans la BDD
et créer les mots clées qui sont ensuite enregister dans la table "elaindex" 

'''
@app.route('/myclass/api/ela_index_all_classes/', methods=['POST','GET'])
@crossdomain(origin='*')
def ela_index_all_classes():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, retval = ela_index_class.ela_index_all_classes()
    return jsonify(status=status, message=retval)


'''
Cette API index la base donnée en se basant sur le title.
La fonction "ela_index_all_classes" va aller chercher chaque cours dans la BDD
et créer les mots clées qui sont ensuite enregister dans la table "elaindex" 

'''
@app.route('/myclass/api/ela_index_all_classes_title/', methods=['POST','GET'])
@crossdomain(origin='*')
def ela_index_all_classes_title():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, retval = ela_index_class.ela_index_all_classes_title()
    return jsonify(status=status, message=retval)



'''
Cette API index la base donnée en se basant sur les videos qui ont une transcription
le champs en question sera : "video_text".
La fonction "ela_index_all_classes" va aller chercher chaque cours dans la BDD
et créer les mots clées qui sont ensuite enregister dans la table "elaindex" 

'''
@app.route('/myclass/api/ela_index_all_classes_video_text/', methods=['POST','GET'])
@crossdomain(origin='*')
def ela_index_all_classes_video_text():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, retval = ela_index_class.ela_index_all_classes_video_text()
    return jsonify(status=status, message=retval)



''' Analyse Youtubes 
'''
@app.route('/myclass/api/ela_index_all_ytubes_video_transcription/', methods=['POST','GET'])
@crossdomain(origin='*')
def ela_index_all_ytubes_video_transcription():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, retval = YTA.ela_index_all_ytubes_video_transcription()
    return jsonify(status=status, message=retval)



'''
Cette API index la base donnée en se basant sur le description.
La fonction "ela_index_all_classes" va aller chercher chaque cours dans la BDD
et créer les mots clées qui sont ensuite enregister dans la table "elaindex" 

'''
@app.route('/myclass/api/ela_index_all_classes_desc/', methods=['POST','GET'])
@crossdomain(origin='*')
def ela_index_all_classes_desc():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, retval = ela_index_class.ela_index_all_classes_desc()
    return jsonify(status=status, message=retval)



'''
Cette API index la base donnée en se basant sur le objectif.
La fonction "ela_index_all_classes" va aller chercher chaque cours dans la BDD
et créer les mots clées qui sont ensuite enregister dans la table "elaindex" 

'''
@app.route('/myclass/api/ela_index_all_classes_obj/', methods=['POST','GET'])
@crossdomain(origin='*')
def ela_index_all_classes_obj():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, retval = ela_index_class.ela_index_all_classes_obj()
    return jsonify(status=status, message=retval)


'''
Cette API index la base donnée en se basant sur les mots clées (keyword).
La fonction "ela_index_all_classes" va aller chercher chaque cours dans la BDD
et créer les mots clées qui sont ensuite enregister dans la table "elaindex" 

'''
@app.route('/myclass/api/ela_index_all_classes_keywords/', methods=['POST','GET'])
@crossdomain(origin='*')
def ela_index_all_classes_keywords():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, retval = ela_index_class.ela_index_all_classes_keywords()
    return jsonify(status=status, message=retval)




'''
Cette API, utilisée dans phase de developpement
est utilisé pour supprimer le token d'un user

Use case : Uniquement en developpement
'''
@app.route('/myclass/api/Dev_del_user_token/', methods=['POST','GET'])
@crossdomain(origin='*')
def Dev_del_user_token():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, retval = dev_function.Dev_del_user_token(payload)
    return jsonify(status=status, message=retval)

'''
Recherche en mode tips
'''
@app.route('/myclass/api/recherche_tips/', methods=['POST','GET'])
@crossdomain(origin='*')
def recherche_tips():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, retval = wp.recherche_tips(payload)
    return jsonify(status=status, message=retval)



'''
Recuperation de l'historique de recherche d'un user
'''
@app.route('/myclass/api/get_stored_recherche/', methods=['POST','GET'])
@crossdomain(origin='*')
def get_stored_recherche():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, retval = wp.get_stored_recherche(payload)
    return jsonify(status=status, message=retval)


'''
Cette API met à jour le password d'un user
'''
'''
Recuperation de l'historique de recherche d'un user
'''
@app.route('/myclass/api/change_user_pwd/', methods=['POST','GET'])
@crossdomain(origin='*')
def change_user_pwd():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, retval = eua.change_user_pwd(payload)
    return jsonify(status=status, message=retval)


'''
Cette API met à jour le l'adresse email principale d'un user
'''

@app.route('/myclass/api/change_uer_email/', methods=['POST','GET'])
@crossdomain(origin='*')
def change_uer_email():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, retval = eua.change_uer_email(payload)
    return jsonify(status=status, message=retval)

'''
Cette API supprime un compte utilisateur tout en gardant la cohérence
des information.

Cela revient à :
1 - Anonyser le compte tous les champ identifiants une personne
(['adr_street', 'adr_city', 'adr_zip', 'adr_country', 'mob_phone','link_facebook', 'link_twitter', 'token'])
2 - Bloquer le compte
3 - Desactiver le compte
'''
@app.route('/myclass/api/delete_user_account/', methods=['POST','GET'])
@crossdomain(origin='*')
def delete_user_account():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, retval = eua.delete_user_account(payload)
    return jsonify(status=status, message=retval)



'''
Cette API verrouille le compte d'un utilisateur
Cela revient à mettre le champ : "locked" à 1

'''
@app.route('/myclass/api/lock_user_account/', methods=['POST','GET'])
@crossdomain(origin='*')
def lock_user_account():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, retval = eua.lock_user_account(payload)
    return jsonify(status=status, message=retval)



'''
Cette API desactive le compte d'un utilisateur
Cela revient à mettre le champ : "active" à 0 et "locked" a 1

'''
@app.route('/myclass/api/desable_user_account/', methods=['POST','GET'])
@crossdomain(origin='*')
def desable_user_account():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, retval = eua.desable_user_account(payload)
    return jsonify(status=status, message=retval)


'''
Cette API enregistre le message d'un utilisateur
Par pour la gestion des message de "contactez-nous".
'''
@app.route('/myclass/api/add_user_message/', methods=['POST','GET'])
@crossdomain(origin='*')
def add_user_message():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, retval = um.add_user_message(payload)
    return jsonify(status=status, message=retval)

'''
Cette API recuperer le message posté par un utilisateur.
Le premier cas d'usage est la recuperation post effectué sur un article par un 
utilisateur
'''
@app.route('/myclass/api/get_user_message/', methods=['POST','GET'])
@crossdomain(origin='*')
def get_user_message():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, retval = um.get_user_message(payload)
    return jsonify(status=status, message=retval)



'''
Cette API ajoute des formation en masse
par exemple avec un fichier CSV
'''

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in MYSY_GV.ALLOWED_EXTENSIONS


@app.route('/myclass/api/add_class_mass/', methods=['POST','GET'])
@crossdomain(origin='*')
def add_class_mass():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    print(request.files)

    if request.method == 'POST':
        # Create variable for uploaded file
        f = request.files['File']

        status, retval = cm.add_class_mass(f, app.config['UPLOAD_FOLDER'], payload)

    return jsonify(status=status, message=retval)

'''
test d'enregistrement d'une image
'''
@app.route('/myclass/api/recordImage/', methods=['POST','GET'])
@crossdomain(origin='*')
def recordImage():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    print(request.files)

    if request.method == 'POST':
        # Create variable for uploaded file
        f = request.files['File']

        status= mycommon.recordImage(f, app.config['UPLOAD_FOLDER'], payload)

    return jsonify(status=status)

'''
Test de recuperation d'une image enregistrée
'''

@app.route('/myclass/api/getRecodedImage/', methods=['POST','GET'])
@crossdomain(origin='*')
def getRecodedImage():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, myimg= mycommon.getRecodedImage(payload)
    return jsonify(status=status, message=myimg)




'''
Cette API gere la connexion d'un partenaire.

Pour memo la connexion d'un partenaire est differente de celle d'un user
Pour le partenaire, en plud du mail, passwd, il faut fournir le token qui est "secrete"
'''
@app.route('/myclass/api/partner_login/', methods=['POST','GET'])
@crossdomain(origin='*')
def partner_login():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    print(request.files)
    status, retval = pa.partner_login(payload)
    return jsonify(status=status, message=retval)


'''
Cette API recuperer tous les articles et avis sur les formations
'''
@app.route('/myclass/api/get_all_articles_avis/', methods=['POST','GET'])
@crossdomain(origin='*')
def get_all_articles_avis():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, retval = aa.get_all_articles_avis(payload)
    return jsonify(status=status, message=retval)



'''
Cette API recupere un article/avis donné
'''
@app.route('/myclass/api/get_articles_avis/', methods=['POST','GET'])
@crossdomain(origin='*')
def get_articles_avis():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, retval = aa.get_articles_avis(payload)
    return jsonify(status=status, message=retval)

'''
Cette API ajouter un article/avis
'''
@app.route('/myclass/api/add_articles_avis/', methods=['POST','GET'])
@crossdomain(origin='*')
def add_articles_avis():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, retval = aa.add_articles_avis(payload)
    return jsonify(status=status, message=retval)


'''
Cette API indexe les articles et avis postés
'''

@app.route('/myclass/api/ela_index_all_articles_avis/', methods=['POST','GET'])
@crossdomain(origin='*')
def ela_index_all_articles_avis():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ",payload)
    status, retval = ela_index_class.ela_index_all_articles_avis()
    return jsonify(status=status, message=retval)


''' 
Cette API recherche un articles ou un avis en se basant sur le
titre de la formation'''
@app.route('/myclass/api/recherche_articles_avis/', methods=['GET','POST'])
@crossdomain(origin='*')
def recherche_articles_avis():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ", payload)
    status, result = aa.recherche_articles_avis(payload)
    return jsonify(status=status, message=result)


''' 
Cette API retourne les articles et avis à la Une'''
@app.route('/myclass/api/get_article_avis_alaune/', methods=['GET','POST'])
@crossdomain(origin='*')
def get_article_avis_alaune():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ", payload)
    status, result = aa.get_article_avis_alaune(payload)
    return jsonify(status=status, message=result)


'''
Cette API reinitialise le mot de passe d'un utilisation
depuis le front office'''
@app.route('/myclass/api/InitUserPasswd/', methods=['GET','POST'])
@crossdomain(origin='*')
def InitUserPasswd():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ", payload)
    status, result = eua.InitUserPasswd(payload)
    return jsonify(status=status, message=result)

'''
Cette API verifie la validité d'un token 
'''
@app.route('/myclass/api/IsUserTokenValide/', methods=['GET','POST'])
@crossdomain(origin='*')
def IsUserTokenValide():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ", payload)
    status, result = eua.IsUserTokenValide(payload)
    return jsonify(status=status, message=result)

'''
Cette API, modifie le pwd d'un user
en partant d'un token.
l'api est utilisé dans le cas d'un process de reinitialisation du pwd
par le user meme'''
@app.route('/myclass/api/Reset_user_pwd_by_token/', methods=['GET','POST'])
@crossdomain(origin='*')
def Reset_user_pwd_by_token():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ", payload)
    status, result = eua.Reset_user_pwd_by_token(payload)
    return jsonify(status=status, message=result)



'''
Cette API envoi l'email de suppression du compte utilisateur.
une suppression se passe tjrs 2 phase : 
pahse 1 : envoi de l'email + blocage du compte
pahse 2 : confirmation depuis l'email recu.
'''
@app.route('/myclass/api/send_mail_delete_user/', methods=['GET','POST'])
@crossdomain(origin='*')
def send_mail_delete_user():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ", payload)
    status, result = eua.send_mail_delete_user(payload)
    return jsonify(status=status, message=result)


'''
Cette API pour des tests perso
'''
@app.route('/myclass/api/mysy_recherche_levenshtein_orig/', methods=['GET','POST'])
@crossdomain(origin='*')
def mysy_recherche_levenshtein_orig():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ", payload)
    status, result = TP.mysy_recherche_levenshtein_orig()
    return jsonify(status=status, message=result)

'''
Cette API est le cron qui traite les emails stockes dans la collection
'user_message'
'''
@app.route('/myclass/api/CronUSerMessage_Mail/', methods=['GET','POST'])
@crossdomain(origin='*')
def CronUSerMessage_Mail():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ", payload)
    status, date_treatment, result = mycommon.CronUSerMessage_Mail()
    return jsonify(status=status, date_treatment = str(date_treatment), message=result)

'''
Juste une API pour tester de ptite choses
'''
@app.route('/myclass/api/OrderClassRandomly/', methods=['GET','POST'])
@crossdomain(origin='*')
def OrderClassRandomly():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ", payload)
    status, result = mycommon.FormationAlaUne()
    return jsonify(status=status,  message=result)


@app.route('/myclass/api/Migration_internal_url/', methods=['GET','POST'])
@crossdomain(origin='*')
def Migration_internal_url():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ", payload)
    status, result = "none", "none", #mycommon.Migration_internal_url()
    return jsonify(status=status,  message=result)


'''
Correction erreur title mymooc.com
'''
@app.route('/myclass/api/Migration_mooc_title/', methods=['GET','POST'])
@crossdomain(origin='*')
def Migration_mooc_title():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ", payload)
    status, result = "none", "none", #mycommon.Migration_mooc_title()
    return jsonify(status=status,  message=result)



'''
Cette API va aller chercher dans la collection "elaindex" 
les mots qui contiennent le mot "mot"'''
@app.route('/myclass/api/GetMotFromElaIndex/', methods=['GET','POST'])
@crossdomain(origin='*')
def GetMotFromElaIndex():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ", payload)
    status, result = mycommon.GetMotFromElaIndex(payload)
    return jsonify(status=status,  message=result)

'''
Cette API retour une formation "coup de coeur" apres
avoir effectué tous les controles
'''
@app.route('/myclass/api/get_class_coup_de_coeur/', methods=['GET','POST'])
@crossdomain(origin='*')
def get_class_coup_de_coeur():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ", payload)
    status, result = cm.get_class_coup_de_coeur(payload)
    return jsonify(status=status,  message=result)


"""
Cette API clean la collecion "elaindex" 
"""
@app.route('/myclass/api/clean_ElaIndex/', methods=['GET','POST'])
@crossdomain(origin='*')
def clean_ElaIndex():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ", payload)
    status, result = mycommon.clean_ElaIndex()
    return jsonify(status=status,  message=result)


"""
Cette API clean les internal url de la collection "myclass" 
"""
@app.route('/myclass/api/clean_internal_url/', methods=['GET','POST'])
@crossdomain(origin='*')
def clean_internal_url():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ", payload)
    status, result = mycommon.clean_internal_url()
    return jsonify(status=status,  message=result)



'''
Cette API retourne les formations par metier
'''
@app.route('/myclass/api/get_class_by_metier/', methods=['GET','POST'])
@crossdomain(origin='*')
def get_class_by_metier():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ", payload)
    status, result = cm.get_class_by_metier(payload)
    return jsonify(status=status, message=result)


'''
Cette API met à jour les formations en ajoutant les metier
'''
@app.route('/myclass/api/UpdateMetier/', methods=['GET','POST'])
@crossdomain(origin='*')
def UpdateMetier():
    status = mycommon.UpdateMetier()
    return jsonify(status=status)



'''
Cette API effectue la migration d'un compte utilisateur 
vers un compte pro (ou compte partenaire)
'''
@app.route('/myclass/api/UpgradetoPro/', methods=['GET','POST'])
@crossdomain(origin='*')
def UpgradetoPro():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ", payload)
    status, result = pa.UpgradetoPro(payload)
    return jsonify(status=status,  message=result)



'''
Cette API recupere les facture d'un client en prenant son tokek
'''
@app.route('/myclass/api/get_invoice_by_customer/', methods=['GET','POST'])
@crossdomain(origin='*')
def get_invoice_by_customer():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ", payload)
    status, result = invoice.get_invoice_by_customer(payload)
    return jsonify(status=status,  message=result)

'''
Cette API recupere les produits et services d'un pack données.
Si le pack n'est pas defini, alors tous les produits valides sont
retournés
'''
@app.route('/myclass/api/get_product_service/', methods=['GET','POST'])
@crossdomain(origin='*')
def get_product_service():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ", payload)
    status, result = PS.get_product_service(payload)
    return jsonify(status=status,  message=result)


"""
Cette API rengristre un mode depayment (CB ou SEPA) 
"""
@app.route('/myclass/api/add_payement_mode/', methods=['GET','POST'])
@crossdomain(origin='*')
def add_payement_mode():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ", payload)
    status, result = invoice.add_payement_mode(payload)
    return jsonify(status=status,  message=result)


"""
Cette API recupere le mode de payement par defaut d'un client
"""
@app.route('/myclass/api/get_payement_mode/', methods=['GET','POST'])
@crossdomain(origin='*')
def get_payement_mode():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ", payload)
    status, result = invoice.get_payement_mode(payload)
    return jsonify(status=status,  message=result)

"""
Cette API recupere les données et crée la commande
"""
@app.route('/myclass/api/createOrder/', methods=['GET','POST'])
@crossdomain(origin='*')
def createOrder():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ", str(payload))
    status, message, order_id = invoice.createOrder(payload)
    return jsonify(status=status,  message=message, order_id=order_id)

"""
Cette API retourne la liste des mots suggerés pour la recherche
"""
@app.route('/myclass/api/Get_Suggested_Word/', methods=['GET','POST'])
@crossdomain(origin='*')
def Get_Suggested_Word():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ", str(payload))
    status, message = mycommon.Get_Suggested_Word()
    return jsonify(status=status,  message=message)


"""
Cette API imprime et envoie les factures aux clients
"""
@app.route('/myclass/api/PrintAndSendInvoices/', methods=['GET','POST'])
@crossdomain(origin='*')
def PrintAndSendInvoices():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ", str(payload))
    status, message = factures.PrintAndSendInvoices()
    return jsonify(status=status,  message=message)


"""
Cette API imprime et envoie les factures aux clients
"""
@app.route('/myclass/api/PutClassNote/', methods=['GET','POST'])
@crossdomain(origin='*')
def PutClassNote():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ", str(payload))
    status, message = mycommon.PutClassNote()
    return jsonify(status=status,  message=message)

"""
Cette API envoie la facture d'un client
"""

@app.route('/myclass/api/GetCustomerInvoice/<token>/<invoiceid>', methods=['GET','POST'])
@crossdomain(origin='*')
def GetCustomerInvoice(invoiceid, token):
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    payload = {}
    payload['token'] = str(token)
    payload['invoiceid'] = str(invoiceid)
    print(" ### payload facture = ", str(invoiceid), " token = ",str(token))
    return factures.GetCustomerInvoice(payload)

"""
API de facturation automatique des commandes 
"""
@app.route('/myclass/api/AutoamticCreateInvoice/', methods=['GET','POST'])
@crossdomain(origin='*')
def AutoamticCreateInvoice():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ", str(payload))
    status, message = factures.AutoamticCreateInvoice()
    return jsonify(status=status,  message=message)

"""
API de excuter une fonction de statistique
"""
@app.route('/myclass/api/GetStat_class_view_old/', methods=['GET','POST'])
@crossdomain(origin='*')
def GetStat_class_view_old():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ", str(payload))
    status, message = Stat.GetStat_class_view_old()
    return jsonify(status=status,  message=message)


"""
API de excuter une fonction de statistique sur la semaine ecoulée
"""
@app.route('/myclass/api/GetStat_class_view/', methods=['GET','POST'])
@crossdomain(origin='*')
def GetStat_class_view():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ", str(payload))
    status, message = Stat.GetStat_class_view(payload)
    return jsonify(status=status,  message=message)



"""
Cette API retourne les STAT des X formations les plus vues d'un client donné sur 
une periode donnée
"""
@app.route('/myclass/api/GetStat_class_view_topX/', methods=['GET','POST'])
@crossdomain(origin='*')
def GetStat_class_view_topX():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ", str(payload))
    status, message = Stat.GetStat_class_view_topX(payload)
    return jsonify(status=status,  message=message)



"""
Cette API retourne les X formations les plus vues d'un client donné sur 
une periode donnée
"""
@app.route('/myclass/api/Get_X_Best_Class_On_Given_period/', methods=['GET','POST'])
@crossdomain(origin='*')
def Get_X_Best_Class_On_Given_period():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ", str(payload))
    status, message = Stat.Get_X_Best_Class_On_Given_period(payload)
    return jsonify(status=status,  message=message)


"""
Cette API retour les statistiques d'une formation données
"""
@app.route('/myclass/api/GetStat_class_by_internal_url/', methods=['GET','POST'])
@crossdomain(origin='*')
def GetStat_class_by_internal_url():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ", str(payload))
    status, message = Stat.GetStat_class_by_internal_url(payload)
    return jsonify(status=status,  message=message)


@app.route('/myclass/api/test_return/', methods=['GET','POST'])
@crossdomain(origin='*')
def test_return():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ", str(payload))
    status, message = Stat.test_return()
    return jsonify(status=status,  message=message)


"""
API de suppression du compte de LS"""
@app.route('/myclass/api/removeLSaccount/', methods=['GET','POST'])
@crossdomain(origin='*')
def removeLSaccount():
    # On recupere le corps (payload) de la requete
    payload = request.form.to_dict()
    print(" ### payload = ", str(payload))
    status, message = mycommon.removeLSaccount()
    return jsonify(status=status,  message=message)

"""
Correction 
"""
@app.route('/myclass/api/correction_collection/', methods=['GET','POST'])
@crossdomain(origin='*')
def correction_collection():
    # On recupere le corps (payload) de la requete
    print(" correction_collection ")
    status, message = mycommon.correction_collection()
    return jsonify(status=status,  message=message)

if __name__ == '__main__':
    print(" debut api")
    context = SSL.Context(SSL.SSLv23_METHOD)
    if (MYSY_GV.MYSY_ENV == "PROD"):
        mycommon.myprint(" ++++  ENVIRONNEMENT PRODUCTION ++++ ")
        mycommon.myprint("++ DATABASE "+MYSY_GV.CONNECTION_STRING+" ++")
        mycommon.myprint("++ DBNAME " + str(MYSY_GV.dbname) + " ++")
        app.run(host='localhost', port=MYSY_GV.MYSY_PORT_PROD, debug=True, threaded=True)
    elif (MYSY_GV.MYSY_ENV == "DEV"):
        mycommon.myprint(" ++++ ENVIRONNEMENT DEVELOPPEMENT ++++")
        mycommon.myprint("++ DATABASE " + MYSY_GV.CONNECTION_STRING + " ++")
        mycommon.myprint("++ DBNAME " + str(MYSY_GV.dbname) + " ++")
        app.run(host='localhost', port=MYSY_GV.MYSY_PORT_DEV, debug=True, threaded=True)



