from flask import Blueprint, request, jsonify, abort
from flask_login import login_required
import http
from app.common.loginutils import admin_required, any_role_required
from app.models.beer_pub import BeerPub
from app.models.product.product import Product
from app.models.user.role import Role
import jsonpickle
from utils.date_utils import to_date
from app import db
from .blueprint import pubmanagement_blueprint

@pubmanagement_blueprint.route('/activebeerpub', methods=['GET'])
@login_required
@any_role_required(Role.get_waiter_id(), Role.get_cash_desk_id())
def active_beer_pub():
    beer_pub = BeerPub.get_active()
    if beer_pub is None:
        return jsonify()
    return jsonify(id=beer_pub.id)

@pubmanagement_blueprint.route('/createbeerpub', methods=['POST'])
@login_required
@admin_required
def create_beer_pub():
    start_date = to_date(request.form['startDate'])
    end_date = to_date(request.form['endDate'])
    if end_date < start_date:
        abort(400, "Start date cannot be before end date!")

    beer_pub = BeerPub.create(start_date, end_date)
    remarks = request.form['remarks']
    Order.create(beerPub, user, products, list(map(float, amounts)), table,
                 paid_at_order, remarks)
    db.session.commit()
    return ("", http.HTTPStatus.NO_CONTENT)


@order_blueprint.route('/newwaiterorder', methods=['POST'])
@login_required
@roles_required(Role.get_waiter_id())
def new_waiter_order():
    return new_order(current_user.user, True)


@order_blueprint.route('/newcashdeskorder', methods=['POST'])
@login_required
@roles_required(Role.get_cash_desk_id())
def new_cash_desk_order():
    return new_order(current_user.user, False)


@order_blueprint.route('/deleteorder', methods=['POST'])
@login_required
@roles_required(Role.get_cash_desk_id())
def delete_order():
    order = Order.get(request.form['id'])
    if order is not None:
        order.delete()
        db.session.commit()
    return ("", http.HTTPStatus.NO_CONTENT)
def cash_desk_role_id():
    return jsonify(id=Role.get_cash_desk_id())