#! /usr/bin/env python
#  -*- coding: utf-8 -*-
#
# Support module generated by PAGE version 4.22
#  in conjunction with Tcl version 8.6
#    May 31, 2019 06:57:34 PM CST  platform: Windows NT


import sys
import time
import paho.mqtt.client
from threading import Thread

mqtt = paho.mqtt.client

try:
    import Tkinter as tk
except ImportError:
    import tkinter as tk
    from tkinter.messagebox import *
try:
    import ttk

    py3 = False
except ImportError:
    import tkinter.ttk as ttk

    py3 = True


def set_Tk_var():
    global vartext_port
    vartext_port = tk.StringVar(value=1883)
    global vartext_username
    vartext_username = tk.StringVar(value='admin')
    global vartext_password
    vartext_password = tk.StringVar(value='123456')
    global vartext_qos
    vartext_qos = tk.StringVar(value=0)
    global vartext_ip
    vartext_ip = tk.StringVar(value='47.93.30.53')
    global vartext_topic
    vartext_topic = tk.StringVar(value='用户')


def btn_version():
    showinfo("版本信息", "当前发送端版本号: v1.0\nmade by liyan on 2019/05/31 \nQQ 2815767386")


def btn_停止订阅被单击():
    client.disconnect()
    client.loop_stop()
    print("已断开与服务器的连接")
    w.TButton_connect.configure(state=tk.TRUE)
    w.TButton_disconnect.configure(state=tk.DISABLED)
    w.TButton_send.configure(state=tk.DISABLED)
    showinfo("连接提示", "已断开与服务的连接！")


def btn_开始订阅被单击():
    ip = vartext_ip.get()
    port = int(vartext_port.get())
    username = vartext_username.get()
    pwd = vartext_password.get()
    dict = {"ip": ip, "port": port, "username": username, "pwd": pwd}
    print(dict)
    if ip != "" and port != "" and username != "" and pwd != "":
        print("服务器连接信息设置格式验证完毕，开始尝试连接...")
        start_connect(ip, port, username, pwd)
    else:
        print("订阅设置有误，请检查后重试！")


def thread_it(func, *args):
    t = Thread(target=func, args=args)
    t.setDaemon(True)
    t.start()


def start_connect(
        ip="47.93.30.53",
        port=1883,
        username="admin",
        pwd="123456"):
    # client_id = "admin" + time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    client_id = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    global client
    # ClientId不能重复，所以使用当前时间。连接方式参数为tcp也可以不写
    client = mqtt.Client(client_id, transport='tcp')
    # 初始化订阅用户和密码 必须设置，否则会返回「Connected with result code 4」
    client.username_pw_set(username, pwd)
    client.on_connect = on_connect  # 打印连接状态
    client.connect(ip, port, 60)  # 开始连接
    global xc1
    xc1 = Thread(target=client.loop_forever)  # 开启客户端阻塞线程
    xc1.setDaemon(True)
    xc1.start()  # 线程启动
    # global xc2
    # xc2 = Thread(target=sendtest) #循环发送消息。
    # xc2.setDaemon(True)
    # xc2.start()


def on_connect(client, userdata, flags, rc):  # 连接初始化函数。连接成功立即开始订阅并启动消息回调函数
    print("Connected with result code " + str(rc))  # 打印连接状态
    if rc == 0:
        print("已成功连接mqtt服务器!")
        showinfo("连接提示", "已成功连接服务器!")
        w.TButton_connect.configure(state=tk.DISABLED)
        w.TButton_disconnect.configure(state=tk.TRUE)
        w.TButton_send.configure(state=tk.TRUE)
    else:
        print("连接失败，请检查服务器连接设置是否正确!")
        showerror("连接提示", "连接失败!错误码 %s\n请检查服务器连接设置是否正确!")


def on_publish(topic, payload, qos):  # 发送函数
    """
    :param topic: 消息主题
    :param payload: 消息内容
    :param qos: 连接质量
    :return:
    """
    client.publish(topic, payload, qos)


def btn_send():
    content = w.Scrolledtext1.get(1.0, tk.END)
    print(content)
    qos = int(vartext_qos.get())
    topic = vartext_topic.get()
    on_publish(topic, content, qos)


def btn_back():
    lens = len(w.Scrolledtext1.get(1.0, tk.END))
    a = float(w.Scrolledtext1.index("insert"))
    b = round((a - 0.1), 1)
    c = round((b + 0.1), 1)
    w.Scrolledtext1.delete(b, c)


def btn_clear():
    w.Scrolledtext1.delete(1.0, tk.END)


def init(top, gui, *args, **kwargs):
    global w, top_level, root
    w = gui
    top_level = top
    root = top
    w.TButton_connect.configure(state=tk.TRUE)
    w.TButton_disconnect.configure(state=tk.DISABLED)
    w.TButton_send.configure(state=tk.DISABLED)


def destroy_window():
    # Function which closes the window.
    global top_level
    top_level.destroy()
    top_level = None


if __name__ == '__main__':
    import sender

    sender.vp_start_gui()
