import threading
import time
import mysqlhelper
class DBOperation(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self._space_dict = {1:{},2:{},3:{}}
        self._command_dict = {1:{},2:{},3:{}}

        self._db = mysqlhelper.MySqLHelper()
        self._isClose = False
    def close(self):
        self._isClose = True

    def query_command_in_unit(self, unit):
        sql = "select * from command_queue WHERE unit=%s"
        return self._db.selectall(sql, unit)
    def query_command_in_unit_and_type(self, unit,type):
        sql = "select * from command_queue WHERE unit=%s and type=%s ORDER BY statu DESC"
        return self._db.selectall(sql, (unit,type))
    def query_command_all(self):
        sql = "select * from command_queue"
        return self._db.selectall(sql)
    def query_space_in_unit(self,unit):
        sql = "select * from space WHERE unit=%s"
        return self._db.selectall(sql,unit)
    def query_space_all(self):
        sql = "select * from space"
        return self._db.selectall(sql)
    def update_space_status(self,space_id,statu):
        sql = "update space set statu=%s where id=%s"
        return self._db.update(sql,(statu,space_id))
    def clear_space_data(self,space_id):
        sql = "update space set car_number=NULL where id=%s"
        return self._db.update(sql,space_id)
    def query_vehicle_primary_key(self,car_number):
        sql = "select primary_key from vehicle where car_number=%s"
        return self._db.selectall(sql,car_number)
    def delete_command(self,car_number):
        sql = "delete from command_queue where car_number=%s"
        return self._db.delete(sql,car_number)
    def get_space_dict(self):
        return self._space_dict
    def get_command_dict(self):
        return self._command_dict
    def get_pick_command_dict(self):
        return self._command_dict
    def run(self):
        while not self._isClose:
            for unit in range(1,4):
                res = self.query_space_in_unit(unit)
                if len(res) > 0 and self._space_dict[unit] != res:
                    self._space_dict[unit] = res

            for unit in range(1,4):
                res = self.query_command_in_unit(unit)
                if len(res) > 0 and self._command_dict[unit] != res:
                    self._command_dict[unit] = res

            time.sleep(0.001)