import datetime
from flask import Blueprint, request, send_file
from flask_jwt_extended import jwt_required
from median.models import LogAstus, MessageAstus, Magasin
import os
import json
import uuid


from ressources.astus.utils import generate_excel_file

astus_logs_blueprint = Blueprint('astus_logs', __name__)


@astus_logs_blueprint.route('/export', methods=['PATCH'])
@jwt_required()
def export_log():
    data = json.loads(request.data)
    headers = data['headers']

    name = os.sep.join(
        [os.getcwd(), "tmp_export", "%s.xlsx" % uuid.uuid4()])

    stocks = get_all_logs(data)
    generate_excel_file(name, headers, stocks, get_obj_log)

    return send_file(name, as_attachment=True)


def get_obj_log(log):
    obj = {
        'utilisateur': log.utilisateur,
        'adresse': log.adresse,
        'level': log.messageastus.niveau,
        'message_err': log.messageastus.message,
        'mag': log.magasin.mag,
        'mag_label': log.magasin.libelle,
        'date': log.chrono,
        'description': log.descriptif,
        'message': log.message,
    }
    return obj


def get_all_logs(data):
    search = data.get('search')
    level = data.get('level')

    ms = level.split(",")

    start = datetime.datetime.strptime(data.get('start_date'), '%d/%m/%Y').date()
    end = datetime.datetime.strptime(data.get('send_date'), '%d/%m/%Y').date()

    if search is None:
        search = ''
    else:
        search = search.strip()

    logs = LogAstus \
        .select(LogAstus, MessageAstus, Magasin) \
        .join(Magasin, on=(Magasin.mag == LogAstus.mag)) \
        .switch(LogAstus) \
        .join(MessageAstus, on=(LogAstus.code_erreur == MessageAstus.pk)) \
        .where((LogAstus.chrono >= start.isoformat()) &
               (LogAstus.chrono <= end.isoformat()) &
               (
                   (LogAstus.utilisateur.contains(search)) |
                   (LogAstus.adresse.contains(search)) |
                   (LogAstus.message.contains(search)) |
                   (LogAstus.descriptif.contains(search)) |
                   (Magasin.libelle.contains(search))
               ) &
               (MessageAstus.niveau << ms)
               ) \
        .order_by(LogAstus.chrono.desc())
    return logs


@astus_logs_blueprint.route('/list', methods=['GET'])
@jwt_required()
def get_logs():
    data = request.args

    logs = get_all_logs(data) \
        .limit(int(data.get('length'))) \
        .offset(int(data.get('start')))

    list_logs = []

    for log in logs:
        list_logs.append(get_obj_log(log))

    return {'data': list_logs
            }, 200
