import json
import time
import re
import datetime

from flask import Blueprint, render_template, session, g, request, redirect, url_for, flash, get_flashed_messages

from bson.objectid import ObjectId
import bson.errors

from views.auth import requires_sso, auth_check
from helpers.eve_central import market_hub_prices
from helpers import conversions

ordering = Blueprint("ordering", __name__, template_folder="templates")


@ordering.route("/", methods=["GET", "POST"])
@ordering.route("/<item>", methods=["GET", "POST"])
@requires_sso("alliance")
def home(item=""):
    cart_item_list = {}
    error_string = request.args.get("error_string")

    bulk_op_update = g.mongo.db.carts.initialize_unordered_bulk_op()
    bulk_run_update = False

    # Change qty if post from this page
    if request.method == "POST" and request.form.get("action") == "qty":
        for key, value in request.form.items():
            if key != "action" and not key.startswith("DataTables"):
                if value.strip():
                    if int(float(value)) != 0:
                        bulk_op_update.find({"_id": session["CharacterOwnerHash"]}).upsert().update({
                            "$set": {"items." + key: int(float(value))}})
                    else:
                        bulk_op_update.find({"_id": session["CharacterOwnerHash"]}).upsert().update({
                            "$unset": {"items." + key: int(float(value))}})
                    bulk_run_update = True