import time

import pymysql as psql
import message_pb2 as message
import google.protobuf.text_format as tf
import threading
class DBSeacher(threading.Thread):
    def __init__(self,ip,port,database,user,password,unit):
        threading.Thread.__init__(self)
        self.ip=ip
        self.port=port
        self.database=database
        self.user=user
        self.password=password
        self.unit=unit
        self._close=False
        self.conn=psql.connect(host=ip,
                               port=port,
                               database=database,
                               charset="utf8",
                               user=user,
                               passwd=password)
        self.led_callback=None
    def set_ledcallback(self,callback):
        self.led_callback=callback

    def close(self):
        self._close=True
        self.join()
        self.conn.close()
    def search_difficulty(self):
        self.conn.begin()
        cursor=self.conn.cursor()
        SQL="select * from space where height>1.55 and unit=%d and car_number IS NULL and statu=0"%self.unit
        suv=cursor.execute(SQL)
        SQL="select * from space where height<=1.55 and unit=%d and car_number IS NULL and statu=0"%self.unit
        small=cursor.execute(SQL)
        SQL="select * from command_queue where statu=0 and type=1 and unit=%d"%self.unit
        cursor.execute(SQL)
        idel_cmds=cursor.fetchall()
        self.conn.commit()
        cursor.close()

        suv_cmd=0
        small_cmd=0
        for cmd in idel_cmds:
            measure_string=cmd[7]
            measure_info=message.measure_info()
            tf.Parse(measure_string,measure_info)
            if measure_info.height>1.55:
                suv_cmd=suv_cmd+1
            elif measure_info.height<=1.55:
                small_cmd=small_cmd+1

        return [small,suv,suv_cmd,small_cmd]



    def run(self):
        while self._close==False:
            space=self.search_difficulty()
            if space==None:
                print("ERROR Search None")
            small,suv,cmd_suv,cmd_small=space
            idle_small=small-cmd_small
            idle_suv=suv-cmd_suv
            if idle_small<0:
                idle_suv=suv-cmd_suv-(-idle_small)
                idle_small=0


            if not self.led_callback==None:
                self.led_callback(idle_suv,idle_suv+idle_small)

            time.sleep(1)







