from array import array
from flask import Flask, jsonify, request
from xmpp import cli
from function import MyQueryClass
from flask_jwt_extended import JWTManager, create_access_token, jwt_required, get_jwt_identity
from datetime import datetime, timedelta
from config import Config
#from OpenSSL import SSL

#context = SSL.Context(SSL.PROTOCOL_TLSv1_2)
#context.use_privatekey_file('server.key')
#context.use_certificate_file('server.crt')
### ssl_context=context in run
myquery = MyQueryClass()
app = Flask(__name__)
app.config.from_object(Config)
jwt1 = JWTManager(app)

@app.route('/auth', methods=['POST'])
def post_auth():
    request_data =request.get_json()
    loginemail = request_data['login_email']
    
    result = myquery.query_select('''
    SELECT * FROM rest_user
    WHERE (rest_user.name=%s OR rest_user.email=%s) AND rest_user.password=%s;
    ''', (loginemail, loginemail, request_data['password'],), True)
    if(result != False):
        return gen_token(result['id'], 5), 201
    else:
        return jsonify({"msg":"Server error!"}), 500

def gen_token(id, minut):
    token = {"access_token" : create_access_token(identity=id, expires_delta=timedelta(minutes=minut))}
    return jsonify(token)

@app.route('/adduser', methods=['POST'])
def get_add():
    request_data = request.get_json()
    proverka = myquery.query_proverka(''' 
    SELECT * FROM rest_user
    WHERE rest_user.name=%s OR rest_user.email=%s;
    ''', (request_data['name'], request_data['email']))
    if(proverka):
        return jsonify({'msg':"User exist!"})
    else:
        result = myquery.query_insert('''
        INSERT INTO rest_user (name, birthday, lastlogintime, insys, idrole, email, password) 
        VALUES (%s, %s, %s, %s, %s, %s, %s)
        RETURNING id;
        ''', \
            (request_data['name'], request_data['reg_date'],\
                request_data['log_time'], request_data['in_sys'],\
                    request_data['role_id'], request_data['email'], request_data['password']))
        if(result != False):
            return jsonify(result), 201
        else:
            return jsonify({"msg":"Server error!"}), 500

@app.route('/user/<int:id>', methods=['GET'])
def get_user(id):
    return jsonify(myquery.query_select('''
    SELECT * FROM rest_user WHERE id = %s;
    ''', (id,), True)), 200

@app.route('/users', methods=['GET'])
#@jwt_required()
def get_show_user():
    result = myquery.query_select('''
    SELECT rest_user.id, rest_user.name, rest_user.birthday, rest_user.insys, rest_role.name AS role_name, rest_user.lastlogintime, rest_user.email, rest_user.password
    FROM rest_user, rest_role
    WHERE rest_user.idrole = rest_role.id
    ORDER BY id ASC;
    ''', (), False)
    if(result != False):
        return jsonify(result), 200
    else:
        return jsonify({"msg":"Server error!"}), 500

@app.route('/deleteuser', methods=['POST'])
def delete_user():
    request_data = request.get_json()
    result = myquery.query_delete('''
    DELETE FROM rest_user
    WHERE id = %s;
    ''', (request_data['id'],))
    if(result):
        return jsonify({"msg":"Success delete!"}), 200
    else:
        return jsonify({"msg":"Server error!"}), 500

@app.route('/updateuser', methods=['POST'])
@jwt_required()
def test_api():
    try:
        request_data = request.get_json()
        result = myquery.query_update(f'''
        UPDATE rest_user
        SET name = %s
        WHERE id = %s;
        ''', (request_data['name'], get_jwt_identity()))
        if(result):
            return jsonify({"msg":"Success update!"}), 200
        else:
            return jsonify({"msg":"User not found!"}), 400
    except:
        return jsonify({"msg":"Server error!"}), 500


@app.route('/testmessage', methods=['POST'])
def send_mess():
    try:
        request_data = request.get_json()
        for to in request_data['to']:
            cli.send_message(request_data['from'], request_data['password'], to, request_data['message'])
        return jsonify({"msg":"Succes send!"}), 200
    except:
        return jsonify({"msg":"Server error!"}), 500


if __name__ == '__main__':
    #from waitress import serve
    #serve(app, host='127.0.0.2', port='8080')
    app.run(host='127.0.0.2', port='8080', debug=True, load_dotenv=True )