from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import *
import random
from Ui_task import Ui_Dialog


class Team_divider(QDialog, Ui_Dialog):
    
    def __init__(self, parent=None):
        super(Team_divider, self).__init__(parent)
        self.setupUi(self)
        
    @pyqtSlot()
    def on_PBwork_clicked(self):
        fileName_choose, filetype = QFileDialog.getOpenFileName(self,  "選取TXT文件")
        filename = fileName_choose.split("/")[-1]
        self.LB.setText(filename)

        num_in_one_group = 8
        group = 1
        text = []
        with open(filename) as f:
            read_data = f.read().splitlines() 
        print("共有 " + str(len(read_data)) + " 位學員")
        random.shuffle(read_data)
        for i in range(len(read_data)):
            if i%num_in_one_group == 0:
                print("-"*20)
                print("group " + str(group) +":")
                group_list = []
                print()
                group_list.append("Team"+" : "+"{"+str(group)+"}"+" Leader : "+read_data[i])
                group_list.append(" Member : ")
                group = group + 1
                print("Leader:"+read_data[i])
            else:
                print("Member:"+read_data[i])
                group_list.append(read_data[i])
            if i%num_in_one_group == 0:
                text.append(group_list)
              
                
            self.TB.setText(str(text))
   
    @pyqtSlot()
    def on_PBsave_clicked(self):
        task, filetype = QFileDialog.getSaveFileName(self, "儲存",".","Text Files(*.txt)") 
        file = open(task,'w')
        text = self.TB.toPlainText()
        file.write(text)
        file.close()
        
if __name__ == '__main__':
    import sys
    from PyQt5.QtWidgets import QApplication
    app = QApplication(sys.argv)
    dlg = Team_divider()
    dlg.show()
    sys.exit(app.exec_())
