#!/usr/bin/env python3

import tkinter as tk
import threading
import pyperclip
import pyautogui
from pynput.keyboard import Controller, Key, Listener

from pynput.mouse import Button, Listener as ListenerMouse, Controller
from pynput import mouse
from pynput import keyboard
from collections import Counter
from  tkinter  import ttk
import win32gui
import pymysql
import time
import easygui as g
import tools

lastSentence = None
#这里记录字符的连续长度
strList = []
#这里记录排序后的数组
copyList = []
#这里记录窗口变化
fileUrlOld = None
#这里记录要被替换的字符串
replaced_string = None
replaced_string1 = None  #分中英文
#这里记录的是实际值
realS = ""
#这里记录上一个按键值
firstBu=None
#这里记录全局的标签
label = "功能"
#
contentList = []




hwnd_title = dict()
"""
智能提示
"""
def intelligent_Tips(sentence,label):
    global contentList
    stock_identification = 0   #0：快捷输入库  1：重要信息库  2：代码库， 3 日常记录库
    # if str(sentence) != "":
    writing_Template_query_all_sql = "SELECT * from  code_query WHERE  content  LIKE '%BBBB%'  and label = '"+label+"'  ORDER BY  count DESC "
    # 查询数据库 list
    all_record = queryMysql(writing_Template_query_all_sql.replace("BBBB",str(sentence).replace("\n","").replace("\r","").replace(" ","")))
    print(all_record)
    # print(writing_Template_query_all_sql.replace("BBBB",str(sentence).replace("\n","").replace("\r","")))
    contentList = []
    for obj in all_record:
        contentList.append(obj.get("content"))
    return contentList

     



#把数据库查询结果转换为json
def sql_fetch_json(cursor: pymysql.cursors.Cursor):
    """
    Convert the pymysql SELECT result to json format
    :param cursor:
    :return:
    """
    keys = []
    for column in cursor.description:
        keys.append(column[0])
    key_number = len(keys)

    json_data = []
    for row in cursor.fetchall():
        print(row)  #java
        # item = dict()
        item = {}
        for q in range(key_number):
            item[keys[q]] = row[q]
        json_data.append(item)

    return json_data

#查询通用接口
def  queryMysql(sql,dbName="personal_product"):
    # 打开数据库连接
    db = pymysql.connect("localhost", "root", "lgc057171", dbName, charset='utf8' )
    # 使用cursor()方法获取操作游标 
    cursor = db.cursor()
    # 使用execute方法执行SQL语句
    cursor.execute(sql)
    # 使用 fetchone() 方法获取一条数据
    # data = cursor.fetchone()
    data = sql_fetch_json(cursor)
    # print(data)
    # 关闭数据库连接
    db.close()
    return data 
# 插入,更新，删除通用接口
def  saveMysql(sql,dbName="personal_product"):
    # 打开数据库连接
    db = pymysql.connect("localhost", "root", "lgc057171", dbName, charset='utf8' )
    # 使用cursor()方法获取操作游标 
    cur= db.cursor()
    # 使用execute方法执行SQL语句
    try:
        cur.execute(sql)
        #提交
        db.commit()
    except Exception as e:
        #错误回滚
        print(e)
        db.rollback() 
    finally:
        db.close()
    return True
def get_all_hwnd(hwnd,mouse):
    if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd):
        hwnd_title.update({hwnd:win32gui.GetWindowText(hwnd)})



def  getHwnd():
    appList = []
    # print(hwnd_title.items())
    for h,t in hwnd_title.items():
        if t is not "":
            t = t.replace("*","").replace(" - Notepad++","")
            t = t.replace("•","").strip()
            tList = t.split(" ")
            if t != "tk":
                appList.append(tList[0].replace("(mysite) - Sublime Text (UNREGISTERED)",""))
    if "tk" == appList[0]:
        print("试试看有没有走到这个地方"+str(appList[1]))
        #
        return  appList[1]
    return appList[0]


test_list = []
def on_copy(sentence):
    global copyList,test_list,label
    if len(sentence)>10:
        return None
        
    test_list = test_list + intelligent_Tips(sentence,label)
    copyList1 = []
    value = sentence 
    # value = event.widget.get()
    # value = value.strip().lower()
    if value == '':
        data = test_list
        copyList1 = test_list
    else:
        data = []
        index = 1
        for item in test_list:
            if value in item.lower():
                data.append(str(index)+","+item)
                copyList1.append(item)
                index = index + 1 
    copyList = copyList1           
    listbox_update(data)



def on_save(sentence):
    global actionFalg,realS
    result = g.buttonbox(msg=str(sentence)[0:300],title="保存到代码库",choices=("功能管理","功能","重要网址","python","java","sql","js","java知识点","html","css","取消"))
    print("选择："+str(result))
    #result = pyautogui.confirm(text=str(sentence)[0:300],title='保存到代码库',buttons=["功能管理","功能","python","java","sql","js","java知识点","html","css","取消"])
    record_insert_sql = "INSERT INTO code_query  (label,content) VALUES ('AAAA','BBBB')"
    if str(result).find("取消") > -1:
        return None
    if str(result).find("功能处理") > -1:
        # pyautogui.hotkey('ctrl','c')
        # sentence =  pyperclip.paste()
        realS = sentence
        # if sentence != copyContent:
        actionFalg = False
        root.attributes("-alpha", 1)
        root.overrideredirect(True)
        root.geometry("+"+str(mouseX)+"+"+str(int(mouseY)+20))
        return None
    # print("实际的result"+str(result))
    if result != None:
        saveMysql(record_insert_sql.replace("AAAA",result.replace("\\", "\\\\").replace("'","\\'")).replace("BBBB",str(sentence).replace("\\", "\\\\").replace("'","\\'")))
        pyautogui.alert(text='录入成功',title='',button='OK') 
def on_keyrelease(sentence):
    global copyList,fileUrlOld,test_list,realS,label
    copyList1 = []
    win32gui.EnumWindows(get_all_hwnd, 0)
    # print("当前最新句柄"+getHwnd())
    fileUrl = getHwnd()
    if fileUrlOld != fileUrl or fileUrlOld == fileUrl:
        fileUrlOld = fileUrl
        test_list = []
        # try:
        abcList = []
        print(fileUrl)
        try:
            with open(fileUrl,"r+",encoding = "utf-8") as f:
                for obj in f:
                    obj = obj.replace("\n","")
                    if obj != "":
                        objList = obj.split(" ")
                        for obj1 in objList:
                            if obj1 not in abcList:
                                number = len(sentence)
                                if obj.find(";"*len(sentence)) > -1 or  obj.find("；"*len(sentence)) > -1:
                                    # print("实际的字符串0是"+str(obj))
                                    sentence = obj.replace("；",";").replace(";"*len(sentence),"").strip()
                                    # print("实际的字符串1是"+str(sentence))
                                    sentence = sentence[len(sentence)-number:len(sentence)]
                                    # print("实际的字符串2是"+str(sentence))
                                    realS = sentence
                                    # print("实际的字符串3是"+str(sentence))
                                abcList.append(obj1.replace(";"*len(sentence),"").replace("；"*len(sentence),""))
        except Exception as e:
            print(e)
        
        test_list = test_list + intelligent_Tips(sentence,label)
        test_list = test_list+abcList
        # except Exception as e:
        #     print("baocuo"+str(e))
    # value = event.widget.get()
    # print(test_list)
    value = sentence
    if value == '':
        data = test_list
        copyList1 = test_list
    else:
        data = []
        index = 1 #
        for item in test_list:#get3
            # print(value)
            if item.lower().find(value.lower())>-1 :
                # print(str(index)+"---"+str(item.lower()))
                data.append(str(index)+","+item)
                copyList1.append(item)
                index = index + 1
    copyList = copyList1             
    listbox_update(data)


def on_keySpace(sentence):
    global copyList,fileUrlOld,test_list,realS,label
    test_list = test_list + intelligent_Tips(sentence,label)
    copyList1 = []
    value = sentence
    if value == '':
        data = test_list
        copyList1 = test_list
    else:
        data = []
        index = 1 #
        for item in test_list:#get3
            # print(value)
            if item.lower().find(value.lower())>-1 :
                # print(str(index)+"---"+str(item.lower()))
                data.append(str(index)+","+item)
                copyList1.append(item)
                index = index + 1
    copyList = copyList1             
    listbox_update(data)


def listbox_update(data):
    # delete previous data
    listbox.delete(0, 'end')
    # sorting data #我1
    # data = sorted(data, key=str.lower)List
    # put new data
    if data != None and data != []:
        for item in data:
            listbox.insert('end', item)
    else:
        listbox.insert('end', "查询结果为空")



def on_select(event):
    global label,actionFalg,clickFlag
    #这里点击则展示全部的信息
    clickFlag = False
    content = ""
    try:
        content = str(event.widget.get(event.widget.curselection()))
    except Exception as e:
        print(e)
    if content == "":
        return False
    if label == "功能":
        # 模拟快捷键，热键
        print("进入功能区")
        root.attributes("-alpha", 0)
        # pyautogui.hotkey('ctrl', 'c')
        #获取粘贴板内容
        if  content == "取消":
            actionFalg = True
            return False
        sentence =  pyperclip.paste()
        #独立的功能区域
        functional_area(content,sentence)
        #这里为了实现功能后，还能继续使用
        actionFalg = True
        # if content == "翻译":
        #     print("进入翻译了---"+sentence)
        # elif content == "格式化Json":
        #     pass

        code_query_update_sql = "UPDATE code_query SET count  = count + 1 WHERE content = 'BBBB'"
        saveMysql(code_query_update_sql.replace("BBBB",content.replace("\\", "\\\\").replace("'","\\'")))
    else:
        root.geometry("+1500+100")
        content =",".join(content.split(",")[1:])
        print(content)
        #这边可以拓展一系列功能
        # print("!!!!!!!!!!!!!!!!!!!!!!!!!")
        # result1 = pyautogui.confirm(text=content,title='功能处理',buttons=["复制","翻译","查询"])
        result1 = g.buttonbox(msg=content[0:300],title="",choices=("复制","翻译","查询","取消"))
        print(result1)
        if None != result1 and str(result1).find("复制")>-1:
            pyperclip.copy(content)
        if None != result1 and str(result1).find("取消") == -1:
            print("进来了----"+content)
            code_query_update_sql = "UPDATE code_query SET count  = count + 1 WHERE content = 'BBBB'"
            saveMysql(code_query_update_sql.replace("BBBB",content.replace("\\", "\\\\").replace("'","\\'")))

    # display element selected on list
    # print('(event) previous:', event.widget.get('active'))
    # print('(event)  current:', event.widget.get(event.widget.curselection()))
    # print('---')

# def on_select(event):

#修改文件内容
def alter(file,old_str,new_str):
    """
    替换文件中的字符串
    :param file:文件名
    :param old_str:就字符串
    :param new_str:新字符串
    :return:
    """
    file_data = ""
    # print("新字符串是"+new_str)
    with open(file, "r", encoding="utf-8") as f:
        for line in f:
            if old_str in line:
                line = line.replace(old_str,new_str)
            file_data += line
    with open(file,"w",encoding="utf-8") as f:
        f.write(file_data)


def fun_timer(obj,flag):
    global lastSentence,copyList,replaced_string,replaced_string1,realS
    # print('Hello Timer!')
    sentence = pyperclip.paste()
    if obj in ["1","2","3","4","5","6","7","8","9","0"] and flag == "1":
        try:
            # print(copyList)
            pyperclip.copy(copyList[int(obj)-1])
            copyResult =  pyperclip.paste()
            # print("老字符串为"+str(realS+replaced_string+str(obj)))
            if replaced_string !=None and fileUrlOld != None:
                pyautogui.hotkey('ctrl', 's')
                alter(fileUrlOld,realS+replaced_string+str(obj),copyResult)
                alter(fileUrlOld,realS+replaced_string1+str(obj),copyResult)
                # alter(fileUrlOld,replaced_string1,copyResult)
                # alter(fileUrlOld,replaced_string,copyResult)
            # copyList = []             
            listbox_update([])
        except Exception as e:
            print("1111"+str(e))
    if flag == "2":
        sentence = "".join(strList[len(strList)-2*int(obj):len(strList)-int(obj)])
        lastSentence = None
        if lastSentence != sentence:
            lastSentence = sentence
            on_keyrelease(sentence)



def go(*args):   #处理事件，*args表示可变参数
    global label,realS
    label = str(comboxlist.get()).strip()
    if label == "功能":
        listbox_update(intelligent_Tips("",label))
    if label != "功能":
        if realS != None:
            # try:
            print("真实值是"+str(realS))
            queryList = intelligent_Tips(realS,label)
            newList = []
            index = 1 
            for obj in queryList:
                newList.append(str(index)+","+obj)
            print("查询的结果为"+str(queryList))
            listbox_update(newList)
            # except Exception as e:
            #     print(e) 
        root.overrideredirect(False)
        root.geometry("+1500+100")

    print(comboxlist.get()) #打印选中的值


root = tk.Tk()

comvalue=tk.StringVar()#窗体自带的文本，新建一个值
comboxlist=ttk.Combobox(root,textvariable=comvalue) #初始化
comboxlist["values"]=("功能","python","重要网址","java","sql","js","java知识点","html","css","取消")
comboxlist.current(0)  #选择第一个
comboxlist.bind("<<ComboboxSelected>>",go)  #绑定事件,(下拉列表框被选中时，绑定go()函数)
comboxlist.pack()


# entry = tk.Entry(root)
# entry.pack()
# entry.bind('<KeyRelease>', on_keyrelease)

def word_count_in_str(string, keyword):
    return len(string.split(keyword))-1


# 监听按压
def on_press(key):
    global strList,replaced_string,replaced_string1,firstBu,test_list,label,keyAction,clickFlag,realS
    # keyAction = True
    keyValue = ""
    try:
        keyValue = key.char
    except Exception as e:
        keyValue = str(key)
    if label != "功能":
        # print(keyValue,firstBu)
        if keyValue not in ["Key.space","Key.enter","Key.ctrl_l","Key.right","Key.shift_r","Key.shift","Key.alt_l"]:
            if keyValue not in ["1","2","3","4","5","6","7","8","9","0"] :
                # print(keyValue)
                if keyValue.find("Key.") == -1:
                    strList.append(keyValue)
                    if len(strList) > 40:
                        strList = strList[len(strList)-40:len(strList)]
                    # print("累加的字符串为"+str(strList))
            elif firstBu != "Key.shift_r":
                test_list = []
                strdd = "".join(strList)
                # print(strList)
                if strdd.find(";;")>-1 or strdd.find("；；")>-1:
                    if ";" in strList[len(strList)-3:len(strList)]  or "；" in strList[len(strList)-3:len(strList)]:
                        fun_timer(keyValue,"1")
            if keyValue in [";"]:
                result = 0
                if len(strList)>10:
                    result = word_count_in_str("".join(strList[len(strList)-10:len(strList)]),";")
                else:
                    result = word_count_in_str("".join(strList),";")
                # print("字符串为"+str("".join(strList[len(strList)-5:len(strList)])))
                # print("出现次数"+str(result))
                if int(result)>1:
                    test_list = []
                    pyautogui.hotkey('ctrl', 's')
                    fun_timer(str(result),"2")
                    replaced_string = ";"*int(result)
                    replaced_string1 = "；"*int(result)
        if firstBu == "Key.shift_r" and keyValue in ["1","2","3","4","5","6","7","8","9","0"]:
            pass
        # elif firstBu == "Key.ctrl_l" and keyValue == "c" or firstBu == "c" and keyValue == "Key.ctrl_l":
        #     # pyautogui.hotkey('ctrl', 'c')
        #     time.sleep(1)
        #     sentence =  pyperclip.paste()
        #     #print("拷贝的内容是---"+sentence)
        #     test_list = []
        #     firstBu = None
        #     keyValue = None
        #     # print("进来这个分支了--"+str(sentence))
        #     on_copy(sentence)
        if firstBu == "Key.ctrl_l" and keyValue == "q" or firstBu == "q" and keyValue == "Key.ctrl_l":
            print("进来了111")
            pyautogui.hotkey('ctrl', 'c')
            sentence =  pyperclip.paste()
            on_save(sentence)

        else:
            firstBu = keyValue
    else:
        print("这里是啥子"+keyValue) 
        # 不晓得为啥多了个C
        if firstBu == "Key.ctrl_l" and keyValue == "Key.space" or firstBu == "Key.space" and keyValue == "Key.ctrl_l":
            print("进入space功能")
            firstBu = None
            keyValue = None
            pyautogui.hotkey('ctrl', 'c')
            sentence =  pyperclip.paste()
            realS = sentence
            on_keySpace(sentence)
            root.attributes("-alpha", 1)
        if firstBu == "Key.ctrl_l" and keyValue == "v" or firstBu == "v" and keyValue == "Key.ctrl_l":
            clickFlag = False
        if  firstBu == "Key.ctrl_l" and keyValue == "q" or firstBu == "q" and keyValue == "Key.ctrl_l":
            # print("进来了222")
            firstBu = None
            keyValue = None
            pyautogui.hotkey('ctrl', 'c')
            sentence =  pyperclip.paste()
            on_save(sentence)
            
        else:
            firstBu = keyValue





    # pass
# 监听按压
def on_release(key):
    pass
# 开始监听
def start_listen():
    with Listener(on_press=on_press,on_release=on_release) as listener:
        listener.join()


# 左键
shoot = 0
# 右键
scope = 1
"""
鼠标事件
"""
last_time = 0
"""
鼠标的坐标
"""
mouseX = 0
mouseY = 0

#执行判断
actionFalg = True

#判断拷贝内容是否修改了
copyContent = None
#加一个键盘判断，如果有任何的键盘操作，则都无法进入鼠标的操作
keyAction = False
#处理标识,如果经过了处理就修改标识，否则，不复制
clickFlag = False
#这里新增一个标识，来标记用户鼠标左键的状态
leftStatus = False
#鼠标持续时间
continueClickTime = 0
def mouse_click(x, y, button, pressed):
    global last_time,copyContent,keyAction,clickFlag,leftStatus,continueClickTime
    # print("简历了")
    global shoot
    global scope
    global label
    global actionFalg
    if pressed:
        leftStatus = True
        # 点击右键
        if button == Button.right:
            scope = 0
        # 点击左键
        if button == Button.left:
            last_time = 0
            shoot = 1
    # print(pressed)
    if pressed == False:
        leftStatus = False
        # root.attributes("-alpha", 0)
        actionFalg = True
        continueTime = last_time
        last_time = 0
        print(button)
        if label == "功能" and continueTime > 5  and button != Button.right and continueClickTime >=1:
            pass
            # print("进来了"+str(continueClickTime))
            # #当复制一次的时候没有操作，证明不需要
            # if actionFalg ==False:
            #     actionFalg = True
            #     root.attributes("-alpha", 0)
            # else:
            #     sentence =  pyperclip.paste()
            #     if sentence != copyContent:
            #         copyContent = sentence
            #         actionFalg = False
            #         root.attributes("-alpha", 1)
            #         root.overrideredirect(True)
            #         root.geometry("+"+str(mouseX)+"+"+str(int(mouseY)+20))
            #         keyAction = True
            #         if clickFlag == False:
            #             pyautogui.hotkey('ctrl','c')
            #         clickFlag = True
            #         keyAction = False
            #     else:
            #         # print("进来了3")
            #         pyautogui.hotkey('ctrl','c')
            #         sentence =  pyperclip.paste()
            #         if sentence != copyContent:
            #             copyContent = sentence
            #             actionFalg = False
            #             root.attributes("-alpha", 1)
            #             root.overrideredirect(True)
            #             root.geometry("+"+str(mouseX)+"+"+str(int(mouseY)+20))
    if not pressed and button == Button.left:
        shoot = 0

def on_move(x, y):
    global last_time,mouseX,mouseY
    mouseX = x
    mouseY = y
    last_time = last_time + 1



"""
监听事件方法
"""
def mouseListener():
    with ListenerMouse(on_click=mouse_click,on_move = on_move) as listener1:
        listener1.join()

import threading
t= threading.Thread(target = start_listen)
t.start()
t1= threading.Thread(target = mouseListener)
t1.start()

oldMouseX = None
oldMouseY = None


#这里主要用来监视复制停留时间
def  clickTime():
    global mouseX,mouseY,leftStatus,continueClickTime,oldMouseX,oldMouseY,label,realS
    while True:
        time.sleep(0.5)
        if leftStatus:
            # print("进来了")
            if oldMouseX == mouseX and oldMouseY == mouseY:
                continueClickTime = continueClickTime + 1
                continueTime = last_time
                if label == "功能" and continueTime > 5  and continueClickTime >=1:
                    root.attributes("-alpha", 1)
                    root.overrideredirect(True)
                    root.geometry("+"+str(mouseX)+"+"+str(int(mouseY)+20))
                    pyautogui.hotkey('ctrl','c')
                    realS = pyperclip.paste()
            else:
                oldMouseX = mouseX
                oldMouseY = mouseY
                continueClickTime = 0
        else:
            continueClickTime = 0



#新启动一个线程，监控按压时长，当时间超过1秒的时候，认为
t2 = threading.Thread(target = clickTime)
t2.start()
#这里是功能大集合
def  functional_area(content,sentence):
    global realS
    try:
        if content == "快捷保存":
            on_save(realS)
        else:
            tools.uncommon_Function_Complete(content,"",sentence)
    except Exception as e:
        print(e)
    
    root.geometry("+1800+100")

listbox = tk.Listbox(root,height=15,width=23)
listbox.pack()
#listbox.bind('<Double-Button-1>', on_select)
listbox.bind('<<ListboxSelect>>', on_select)
listD = listbox_update(intelligent_Tips("","功能"))
print(listD)
if listD != None and listD != []:
    for obj in listD:
        listbox.insert('end', obj)
# listbox_update(listbox_update(intelligent_Tips("","功能")))
root.geometry("+1500+100")
root.attributes("-alpha", 0)
root.wm_attributes('-topmost',1)
root.mainloop()
