import biz


class Model(dict):

    def __init__(self):
        self.db = biz.getDB()
        self.cursor = self.db.getCursor()
        self.conn = self.db.getConn()
        pass

    def query(self, sql, args=None):

        self.cursor.execute(sql, args)
        res = self.cursor.fetchall()
        return res

    def execute(self, sql, args=None):
        try:
            self.cursor.execute(sql, args)
            self.conn.commit()
        except BaseException as e:
            print(e)

    def select(self, conditions={}):
        where = fields = limit = orderby = ''
        limit = 'limit 1 offset 0'
        if 'where' in conditions:
            where = ' where ' + conditions['where']
        if 'fields' in conditions:
            fields = '  ' + conditions['fields']
        if 'limit' in conditions:
            limit_d = conditions['limit'].split(',')
            limit = ' limit ' + limit_d[0] + ' offset ' + limit_d[1]
        if 'orderby' in conditions:
            orderby = '  order by ' + conditions['orderby']
        s = "select %s from \"%s\" %s %s %s " % (fields, self.table_name, where, orderby, limit)
        return self.query(s)

    def update(self, data, where=''):
        values = []
        if where != '':
            where = ' where %s' % (where)

        for index in data:
            s = "%s='%s'" % (index, data[index])
            values.append(s)
        sql = "update \"%s\" set %s  %s" % (self.table_name, ','.join(values), where)
        return self.execute(sql)

    def save(self, data):
        fields = []
        values = []
        vls = ''

        for index in data:
            fields.append(index)
            values.append(data[index])
        if vls == '':
            vls = ''
        else:
            vls = vls + ','
        vls = vls + "('%s')" % '\',\''.join('%s' % id for id in values)
        sql = "insert into \"%s\"(%s) values %s" % (self.table_name, ','.join(fields), vls)
        return self.execute(sql)
