import datetime
import time

import async_communication as cmt
import PushCommand as PC
import message_pb2 as message
import google.protobuf.text_format as tf

#mq参数
mq_ip="192.168.1.233"
mq_port=5672
mq_user="zx"
mq_password="zx123456"
ex_name="command_ex"

#db参数
db_ip="192.168.1.233"
db_port=3306
db_name="ct_project"
db_user="zx"
db_password="zx123456"

#rabbitmq
g_rabbitmq=cmt.RabbitAsyncCommunicator(mq_ip,mq_port,mq_user,mq_password)
#DB
g_DBcommand=PC.DBCommand(db_ip,db_port,db_name,db_user,db_password)

def command_enqueue_callback(table):
    print("收到入队请求:%s"%table)
    table=g_DBcommand.push_command(table)
    if table==None:
        return
    command_type=g_DBcommand.table_type(table)

    if command_type=="park":
        cmd=message.park_table()
        tf.Parse(table,cmd)
        response_port="park_response_%d_port"%(cmd.terminal_id)
    else:
        cmd=message.pick_table()
        tf.Parse(table,cmd)
        response_port="pick_response_%d_port"%(cmd.terminal_id)

    if cmd.statu.execute_statu==message.eNormal:
        #指令入队正常
        port="count_command_signal_%d_port"%cmd.unit_id
        g_rabbitmq.publish(ex_name,port,table)   #推送指令作为计数
        print("%s OK : %s指令 %s入队成功 key:%s 单元号：%d"%(datetime.datetime.now(),command_type,cmd.car_number,cmd.primary_key,cmd.unit_id))
    else:
        print("%s ERROR : %s指令 %s入队失败 : %s 单元号:%d"%(datetime.datetime.now(),command_type,cmd.car_number,cmd.statu.statu_description,cmd.unit_id))
    print("发送反馈 ex:%s,port:%s"%(ex_name,response_port))
    g_rabbitmq.publish(ex_name,response_port,table)

if __name__ == '__main__':
    #消费指令消息
    print("入队节点启动----")
    cmd_callbacks=[["command_enqueue_queue",command_enqueue_callback]]
    g_rabbitmq.Init(cmd_callbacks,None)

    #发送自身状态
    # while True:
    #     statu=message.STATU
    #     statu=message.eNormal
    #     g_sender.send(tf.MessageToString(statu,as_utf8=True),"statu_ex","enqueue_node_statu_port")
    #     time.sleep(1)

    g_rabbitmq.start()
    g_rabbitmq.join()


