from app import app
from flask import request, jsonify
from db.product import Product


@app.route('/products', methods=["GET"])
def search_products():
    tags = request.args.get('tags')
    if tags is None:
        tags = []
    else:
        tags = tags.split(',')
    count = request.args.get('count')
    if count is None:
        count = 5
    else:
        count = int(count)
    r = Product.search(count=count, tags=tags)
    return jsonify(r)


@app.route('/products', methods=["POST"])
def add_product():
    p1 = Product(name="Lenovo ThinkPad TH230", price=193000000, tags=["laptop", "pc", "computer", "lenovo", "thinkpad"], available=int(50))
    p2 = Product(name="MSI 127", price=308000000, tags=["laptop", "pc", "computer", "msi", "gaming"], available=int(20))
    p1.store()
    p2.store()
    return jsonify({"id": [p1.get_id(), p2.get_id()]})
