import json
import logging
import os
import uuid

from flask import Blueprint, request, send_file, session
from flask_jwt_extended import jwt_required

from peewee import fn
from median.models import Magasin, Product, Stock, User
from ressources.astus.utils import generate_excel_file

riedl_stock_blueprint = Blueprint('riedl_stock', __name__)

logger = logging.getLogger('median')


def get_obj_stock_price(stk):
    obj = {
        'reference': stk.reference,
        'designation': stk.product.designation,
        'nb_box': stk.nb_box,
        'qty': stk.qty,
        'unit_price': stk.product.prix_unit,
        'total_price': stk.total_price
    }

    return obj


def get_obj_stock(stk):
    obj = {
        'reference': stk.reference,
        'designation': stk.product.designation,
        'nb_box': stk.nb_box,
        'qty': stk.qty,
    }

    return obj


@riedl_stock_blueprint.route('<string:mag_pk>/export', methods=['PATCH'])
@jwt_required()
def export_stock(mag_pk):
    data = json.loads(request.data)

    headers = data['translations']

    user_id = session['user_id']

    profil = User.select(User.profil).where((User.isEnabled == 1) & (User.pk == user_id)).get()

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

    stocks = (Stock.select(Stock.reference, Product.designation, Product.prix_unit,
                           fn.COUNT(1).alias('nb_box'), fn.SUM(Stock.quantite).alias('qty'),
                           fn.SUM(Product.prix_unit).alias('total_price'))
              .join(Product, on=Product.reference == Stock.reference)
              .join(Magasin, on=Magasin.mag == Stock.magasin)
              .where((Magasin.pk == mag_pk) & (Magasin.eco_type == 'L'))
              .group_by(Stock.reference, Product.designation, Product.prix_unit)
              .order_by(Product.designation))
    auth_profils = ['ECO-DEX', 'DEENOVA', 'PHARMACIEN', 'ADMIN']
    generate_excel_file(name, headers, stocks,
                        get_obj_stock_price if any(p == profil for p in auth_profils) else get_obj_stock)

    return send_file(name, as_attachment=True)
