
import os
import sqlite3

file_db = 'app.db'

if os.name == 'posix':
    home = 'HOME'
    directory = '.tryton'
elif os.name == 'nt':
    home = 'USERPROFILE'
    directory = 'AppData/Local/tryton'

_directory = os.path.join(os.getenv(home), directory)
localfile = os.path.join(_directory, file_db)


class LocalDB(object):
    def __init__(self, params=None):
        self.conn = sqlite3.connect(localfile)

    def create_table_config(self):
        cursorObj = self.conn.cursor()
        cursorObj.execute("CREATE TABLE IF NOT EXISTS configuration( \
            'id' INTEGER PRIMARY KEY, \
            'synchronized_date' DATETIME, \
            'company_id' INTEGER, \
            'company_name' TEXT, \
            'defualt_party_id' INTEGER, \
            'defualt_party_name' TEXT \
        )")
        self.conn.commit()

    def create_table_product(self):
        cur = self.conn.cursor()
        cur.execute("CREATE TABLE IF NOT EXISTS product( \
            'id' INTEGER PRIMARY KEY, \
            'code' TEXT, \
            'write_date' DATE, \
            'barcode' TEXT, \
            'template.name' TEXT, \
            'description' TEXT, \
            'quantity' TEXT, \
            'template.account_category' INTEGER, \
            'template.sale_price_w_tax' REAL \
        )")
        self.conn.commit()

    def get_config(self):
        cur = self.conn.cursor()
        cur.execute("SELECT id, synchronized_date FROM configuration")
        config_ = cur.fetchall()
        if config_:
            return config_[0]

    def set_config(self, config):
        cur = self.conn.cursor()
        cur.execute("INSERT INTO configuration(id, synchronized_date, company_id) \
            VALUES(1, '2010-01-01 00:00:00', ?)", config)
        self.conn.commit()

    def set_config_sync(self, config_dt):
        cur = self.conn.cursor()
        cur.execute("UPDATE configuration SET synchronized_date=?", [config_dt])
        self.conn.commit()

    def get_local_products(self):
        cur = self.conn.cursor()
        cur.execute("SELECT id FROM product")
        rows = cur.fetchall()
        rows_ = [r[0] for r in rows]
        return rows_

    def update_products(self, products, local_products):
        to_create = []
        to_update = []
        for p in products:
            if p[0] not in local_products:
                to_create.append(p)
            else:
                to_update.append([p[1], p[4], float(p[7]), p[6], p[0]])

        if to_create:
            cur = self.conn.cursor()
            cur.executemany("INSERT INTO product(id, write_date, code, \
                barcode, 'template.name', description, \
                'template.account_category', 'template.sale_price_w_tax') \
                VALUES(?, ?, ?, ?, ?, ?, ?, ?)", to_create)
            self.conn.commit()

        if to_update:
            cur = self.conn.cursor()
            for rec in to_update:
                cur.execute('UPDATE product SET write_date=?, "template.name"=?,\
                    "template.sale_price_w_tax"=?, "template.account_category"=? \
                    WHERE id=?', rec)
            self.conn.commit()

    def find_product_by_id(self, product_id):
        cur = self.conn.cursor()
        query = "SELECT * FROM product WHERE id=?"
        cur.execute(query, (product_id,))
        res = cur.fetchall()
        return res[0]

    def find_product_elastic(self, domain, limit):
        self.conn.row_factory = lambda c, r: dict(
            zip([col[0] for col in c.description], r)
        )
        cur = self.conn.cursor()
        clauses = []

        for d in domain:
            clause1 = '"{}" LIKE "{}"'.format(d[1][0], d[1][2])
            clause2 = '"{}" LIKE "{}"'.format(d[2][0], d[2][2])
            clause3 = '"{}" LIKE "{}"'.format(d[3][0], d[3][2])
            clause_ = '(' + clause1 + ' OR ' + clause2 + ' OR ' + clause3 + ')'
            clauses.append(clause_.upper())

        if len(clauses) > 1:
            _clause = ' AND '.join(clauses)
        else:
            _clause = clauses[0]
        query = "SELECT * FROM product WHERE {}".format(_clause)

        cur.execute(query)
        rows = cur.fetchall()
        return rows

    # def do_query(self):
    #     c = self.conn.cursor()
    #     c.execute(query)
    #     rows = c.fetchall()
    #     self.conn.commit()
    #     self.conn.close()
    #     for row in rows:
    #         print(row)


if __name__ == "__main__":
    store = LocalDB()
    store.create_table()
    store.get_local_products()
