import time
import asyncio
import async_communication as ASC
import  ExportIO as EIO
import google.protobuf.text_format as tf
import threading
import DatabaseSearchPickCmd as DBS
import message_pb2 as message
import queue
#db参数
db_parameter={"dbname":"ct_project","ip":"192.168.1.233","port":3306,"user":"zx","password":"zx123456"}

rabbitmq_parameter={"ip":"192.168.1.233","port":5672,"user":"zx","password":"zx123456"}

#[单元号，出口号，单片机ip，port]
mcpu_paramters=[[1,1, "192.168.1.130", 40004],
                [2,2, "192.168.1.131", 40004],
                [2,3, "192.168.1.132", 40004],
                [2,4, "192.168.1.133", 40004],
                [3,5,"192.168.1.134",40004],
                [3,6,"192.168.1.135",40004]
                ]

# mcpu_paramters=[[2,3,"192.168.1.132",40004]]

g_rabbitmq=ASC.RabbitAsyncCommunicator(rabbitmq_parameter["ip"],rabbitmq_parameter["port"],
                                       rabbitmq_parameter['user'],rabbitmq_parameter['password'])
g_db=DBS.DBSeacherPickCmd(db_parameter["ip"],db_parameter["port"],db_parameter["dbname"],
                        db_parameter["user"],db_parameter["password"])
g_exports={}


def user_leave_callback(id):
    print("出口：%d 用户已经离开,删除出口取车指令"%(id))
    g_db.delete_cmd(id)


if __name__=="__main__":
    print("出口 danpianji")

    for parameter in mcpu_paramters:
        id=parameter[1]
        if not g_exports.get(id)==None:
            raise("出口单片机id重复")
        g_exports[id]=EIO.ExportIO(parameter,rabbitmq_parameter)
        g_exports[id].SetUserLeaveCallback(user_leave_callback)

    for _,export in g_exports.items():
        export.start()

    while True:
        pickcmds=g_db.search_pickcmd()
        print(pickcmds)
        if len(pickcmds)>0:
            for cmd in pickcmds:
                table=message.pick_table()
                table.car_number=cmd[0]
                table.primary_key=cmd[1]
                table.unit_id=cmd[2]
                table.queue_id=cmd[3]
                table.export_id=cmd[8]
                print(table)
                if not table.export_id==None:
                    export=g_exports.get(table.export_id)
                    if not export==None:
                        # if export.export_idle()==False:
                        if export._retry_count < 5:
                            export.open_door(table)
                        else :
                            g_db.close()
                            print("database restart")
                            g_db.__init__(db_parameter["ip"],db_parameter["port"],db_parameter["dbname"],
                                          db_parameter["user"],db_parameter["password"])

        time.sleep(1)

    for _,export in g_exports.items():
        export.join()

