import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QTextEdit, QFileDialog
import cppy.cp_util as util

# 工具函数
def extract_words(path_to_file):    
    return util.extract_words(path_to_file)

def frequencies(word_list):
    return util.get_frequencies(word_list)

def sort(word_freq):
    return util.sort_dict(word_freq)

class MenuApp(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('终端菜单')
        self.setGeometry(100, 100, 400, 300)

        # 创建按钮
        self.openFileBtn = QPushButton('上传并打开文件', self)
        self.continueBtn = QPushButton('继续', self)
        self.exitBtn = QPushButton('退出', self)

        # 创建文本编辑框
        self.textEdit = QTextEdit(self)
        self.textEdit.setReadOnly(True)

        # 布局
        layout = QVBoxLayout()
        layout.addWidget(self.openFileBtn)
        layout.addWidget(self.continueBtn)
        layout.addWidget(self.exitBtn)
        layout.addWidget(self.textEdit)

        self.setLayout(layout)

        # 信号连接到槽
        self.openFileBtn.clicked.connect(self.openFile)
        self.continueBtn.clicked.connect(self.clearText)
        self.exitBtn.clicked.connect(self.close)

    def openFile(self):
        options = QFileDialog.Options()
        fileName, _ = QFileDialog.getOpenFileName(self, "上传并打开文件", "", "All Files (*);;Text Files (*.txt)", options=options)
        word_freqs = sort( frequencies(extract_words( fileName )) )    
        s = ''
        for (w, c) in word_freqs[ :10 ]:
            s = s +  w + '-' + str(c)+'\n'
        self.textEdit.setText(s)
        

    def clearText(self):
        self.textEdit.clear()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MenuApp()
    ex.show()
    sys.exit(app.exec_())