#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# cd 0intellpy, python iden.py,pyuic5 -x iden.ui -o iden_UI.py, pyinstaller -F -w --icon=qq3.ico iden.py
# 若import 沒有成功，代表你的python缺程式庫，需要安裝，如  pip install pandas,  pip install csv, pip install sounddevice...

import os
import sys
import pandas
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMessageBox, QFileDialog, QApplication, QInputDialog
from PyQt5.QtGui import QPixmap
import sounddevice as sd
import soundfile as sf
from os import path
import csv
import random

from iden_UI import Ui_MainWindow as qq_Ui #pyqt5的UI連接檔設定

class ListenUi(QtWidgets.QMainWindow, qq_Ui):
    def __init__(self):
        super(ListenUi, self).__init__()
        self.setupUi(self)
        self.preButton.clicked.connect(self.preone)
        self.nextButton.clicked.connect(self.nextone)
        self.againButton.clicked.connect(self.playagain)
        self.left_Button.clicked.connect(self.leftButton_play)
        self.right_Button.clicked.connect(self.rightButton_play)
        self.Button_2.clicked.connect(self.judge2)
        self.Button_1.clicked.connect(self.judge1)
        self.actionwave_Directory.triggered.connect(self.readcsv)
        self.actionListener_ID.triggered.connect(self.Listener_IDset)
        self.actionSave_textFile.triggered.connect(self.savefile)
        self.actionHelp.triggered.connect(self.showhelp)
        self.actionAbout.triggered.connect(self.showAbout)
        self.actiondir.triggered.connect(self.setwavdir)
        self.actionClear_textBox.triggered.connect(self.Reset)
        self.nextButton.setEnabled(False)
        self.preButton.setEnabled(False)
        self.Button_1.setEnabled(False)
        self.Button_2.setEnabled(False)
        self.left_Button.setEnabled(False)
        self.right_Button.setEnabled(False)
        self.againButton.setEnabled(False)
        self.csvfile="qiden.csv"
        self.item=0
        self.wavpath='./stiw'
        self.Current_dir.setText(str(self.wavpath))
        self.textBrowser.clear()
        self.comboBox.setCurrentIndex(0)
        
        self.pic1="mon1.jpg"  #圖檔
        self.pic2="mon3.jpg"
        
        self.left_Button.setIcon(QtGui.QIcon(self.pic1))
        self.left_Button.setIconSize(QtCore.QSize(450,350))
        self.right_Button.setIcon(QtGui.QIcon(self.pic2))
        self.right_Button.setIconSize(QtCore.QSize(450,350))
        
    def Reset(self):
        self.textBrowser.clear() 
        self.nextButton.setEnabled(False)
        self.preButton.setEnabled(False)
        self.Button_1.setEnabled(False)
        self.Button_2.setEnabled(False)
        self.left_Button.setEnabled(False)
        self.right_Button.setEnabled(False)
        self.againButton.setEnabled(False)
        self.item=0
        self.textBrowser.clear()
        self.itemno.setText(str(0))
        self.comboBox.setCurrentIndex(0)
    
    def setwavdir(self):
        self.wavpath = QtWidgets.QFileDialog.getExistingDirectory(self, 'Select Folder')
        if self.wavpath:
            self.Current_dir.setText(str(self.wavpath))
        else:
            QMessageBox.information(self, 'error!', "音檔目錄沒有重新設定，預設為./stiw")
            self.wavpath='./stiw'    
        
    def Listener_IDset(self):
        #self.textBrowser.clear()
        juadeno, done1 = QtWidgets.QInputDialog.getText(self, '輸入受試者編號/ID', 'Enter Listeners ID:')
        line0= '受試者編號/ID: '+ str(juadeno)+'\n'  
        if done1:
            self.textBrowser.append(line0)
    
    def Randomseq(self):
        with open(self.csvfile, 'r') as input_file:
            csv_reader = csv.reader(input_file)
            rows = list(csv_reader)

        # Shuffle the rows (excluding the header row)
        header_row = rows[0]
        data_rows = rows[1:]
        random.shuffle(data_rows)

        # Write the shuffled rows to a new CSV file
        with open('output.csv', 'w', newline='') as output_file:
            csv_writer = csv.writer(output_file)
            csv_writer.writerow(header_row)
            csv_writer.writerows(data_rows)
 
        self.csvfile='output.csv'

    
    def readcsv(self):
        filename, filter = QFileDialog.getOpenFileName(self, '開啟csv檔案', 
            './', 'CSV files (*.csv)')
        if filename:
            self.csvfile=filename
        else:
            self.csvfile="idenq.csv"
        
        if self.comboBox.currentText() == "Yes" :
            print("use randomized order")
            self.Randomseq()  #隨機順序
        else:
            pass
        
        try:
            df = pandas.read_csv(self.csvfile)

        except FileNotFoundError:
            original_data= pandas.read_csv("idenq.csv")
            print('***file not found')
        
        self.filelist=df['Qwavf'].tolist()
        self.left_filelist=df['L_wavf'].tolist()
        self.right_filelist=df['R_wavf'].tolist()

        self.totalitem =len(self.left_filelist)
        self.textBrowser.append('題號,題目, Lwavefile, Rwavefile, 反應')
        self.nextButton.setEnabled(True) 
    
    def nextone(self):
        if self.item < self.totalitem:  
            self.item = self.item + 1
            self.current_w = self.filelist[self.item-1]
            self.pfilename = "%s/%s" % (self.wavpath,str(self.current_w))
            self.current_L = self.left_filelist[self.item-1]
            self.Lpfilename = "%s/%s" % (self.wavpath,str(self.current_L))
            self.current_R = self.right_filelist[self.item-1]
            self.Rpfilename = "%s/%s" % (self.wavpath,str(self.current_R))
            #print(self.pfilename,self.Lpfilename,self.Rpfilename)
            self.Current_dir.setText(str(self.pfilename))
            self.itemno.setText(str(self.item))
            self.wavplay()
            self.preButton.setEnabled(True)
            self.againButton.setEnabled(True)
            self.left_Button.setEnabled(True)
            self.right_Button.setEnabled(True)
            self.Button_1.setEnabled(False)
            self.Button_2.setEnabled(False)                 
        else:
            QMessageBox.information(None, '題目', "沒有了!   ")
   
    def preone(self):
        if self.item > 1 :
            self.item=self.item-1
            #print(self.item)
            self.current_w=self.filelist[self.item-1]
            self.pfilename = "%s/%s" % (self.wavpath,str(self.current_w))
            self.Current_dir.setText(str(self.pfilename))
            self.itemno.setText(str(self.item))
            self.current_L = self.left_filelist[self.item-1]
            self.Lpfilename = "%s/%s" % (self.wavpath,str(self.current_L))
            self.current_R = self.right_filelist[self.item-1]
            self.Rpfilename = "%s/%s" % (self.wavpath,str(self.current_R))
            self.wavplay()
            self.preButton.setEnabled(True)
            self.left_Button.setEnabled(True)
            self.right_Button.setEnabled(True)
            self.Button_1.setEnabled(False)
            self.Button_2.setEnabled(False)         
        else:
            QMessageBox.information(None, '題目', "沒有了!   ")     
              
    def wavplay(self):
        try:
            data, fs = sf.read(self.pfilename, dtype='int16')
            sd.play(data, fs)
            #sd.wait()
        except:
            print("cannot find the wav file")
            QMessageBox.information(None, 'error!', "cannot find the wav file")
    
    def leftButton_play(self):
        try:
            data, fs = sf.read(self.Lpfilename, dtype='int16')
            sd.play(data, fs)
            self.Button_1.setEnabled(True)
            self.Button_2.setEnabled(True)
            #sd.wait()
        except:
            print("cannot find the wav file")
            QMessageBox.information(None, 'error!', "cannot find the wav file")
            
    def rightButton_play(self):
        try:
            data, fs = sf.read(self.Rpfilename, dtype='int16')
            sd.play(data, fs)
            self.Button_1.setEnabled(True)
            self.Button_2.setEnabled(True)
            #sd.wait()
            
        except:
            print("cannot find the wav file")
            QMessageBox.information(None, 'error!', "cannot find the wav file")
    
    def playagain(self):
        self.current_w=self.filelist[self.item-1]
        self.pfilename = "%s/%s" % (self.wavpath,str(self.current_w))
        self.Current_dir.setText(str(self.pfilename))
        #print(self.pfilename)
        self.itemno.setText(str(self.item))
        self.wavplay()
        self.preButton.setEnabled(True)
        self.Button_1.setEnabled(True)
        self.Button_2.setEnabled(True)
 
    def judge1(self):
        line1 = str(self.item)+','+str(self.current_w)+','+str(self.current_L)+','+str(self.current_R)+','+ 'resp: L'
        self.textBrowser.append(line1)
        self.Button_1.setEnabled(False)
        self.Button_2.setEnabled(False)
        
    def judge2(self):
        line2 = str(self.item)+','+str(self.current_w)+','+str(self.current_L)+','+str(self.current_R)+','+ 'resp: R'
        self.textBrowser.append(line2)
        self.Button_1.setEnabled(False)
        self.Button_2.setEnabled(False)
  
    def savefile(self):
        S__File = QtWidgets.QFileDialog.getSaveFileName(None,'結果存檔','/', "Text Files (*.txt)")
        #Text0 = self.textEdit.toPlainText()
        Text = self.textBrowser.toPlainText() 
        if S__File[0]:
            outfile = S__File[0]       
        else:
            outfile='resp.txt'
        
        with open(outfile, 'a') as file:
            file.write(Text)      
            file.close()
    
    def showhelp(self): 
        QMessageBox.information(None, 'Welcome!', "1.首先要先編好csv檔(格式請參照原附檔注意不能有空格)，\n2.檢查喇叭音量並於[設定]設定好csv檔和音檔目錄位置，再按下[下一題]按鈕即開始播放題目音，再分別按下左右兩隻動物播放聲音，之後判斷題目音是和左右哪一隻聲音一樣，再按下下方的[是他]按鈕完成該題作答，之後再按[下一題]繼續，\n 3.全部完成後可將文字框的反應資料存檔(.txt檔案),\n 4.若要隨機順序，需要一開始時即選擇隨機'Yes'，之後再設置csv檔")

    def showAbout(self):
        QMessageBox.information(None,'開發','此程式為國立高雄師範大學 聽語研究所 鄭靜宜教授開發，\n 敬請指教，jengyi12345@gmail.com')   
        
if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    a = ListenUi()
    a.show()
    sys.exit(app.exec_())     