import sqlite3
import requests
import constants
import helpers

def setup_db():
    con = sqlite3.connect(constants.DB)
    cur = con.cursor()
    cur.execute("CREATE TABLE IF NOT EXISTS amazon(id INTEGER PRIMARY KEY AUTOINCREMENT, \
                timestamp DATETIME DEFAULT CURRENT_TIMESTAMP, tg_user TEXT, tg_group TEXT, \
                tg_user_id INTEGER, tg_group_id INTEGER, url TEXT, referurl TEXT, price TEXT, \
                title TEXT, image TEXT)")
    con.close()

def add_product(tg_user, tg_group, tg_user_id, tg_group_id, url, referurl, title, price, image):
    con = sqlite3.connect(constants.DB)
    cur = con.cursor()
    cur.execute(f"INSERT INTO amazon (tg_user, tg_group, tg_user_id, tg_group_id, url, referurl, price, title, image) \
        VALUES ('{tg_user}', '{tg_group}', {tg_user_id}, {tg_group_id}, '{url}', '{referurl}', '{price}', '{title}', '{image}')")
    product_id = cur.lastrowid
    con.commit()
    con.close()

    try:
        response = requests.get(image, headers=constants.HEADERS)
        file = open(f"/app/data/images/products/{product_id}.jpg", "wb")
        file.write(response.content)
        file.close()
    except:
        pass

    return product_id

def check_product(referurl, price):
    con = sqlite3.connect(constants.DB)
    cur = con.cursor()
    cur.execute(f"SELECT * FROM amazon WHERE referurl='{referurl}' ORDER BY id DESC")
    result = cur.fetchone()

    if result is None:
        helpers.logging.info("New entry, creating in DB")
        return False
    else:
        helpers.logging.info("Already exists, checking price")
        if price == result[8]:
            helpers.logging.info("Price is the same, retrieving link")
            return result[0]
        else:
            helpers.logging.info("Price is different, creating new entry in DB")
            return False