#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# cd aacpy, python aacpyqt1.py,pyuic5 -x aacp1.ui -o aacp1_UI.py, pyinstaller -F -w --icon=aac.ico aacpyqt1.py

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QPushButton, QStackedWidget
import os
import sys
import csv
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMessageBox, QFileDialog, QApplication, QInputDialog
#from PyQt5.QtGui import QPixmap, QImage
import soundfile as sf
import sounddevice as sd
import wave

from aacp1_UI import Ui_MainWindow as UI_Page1
from aacp2_UI import Ui_MainWindow as UI_Page2
from aacp3_UI import Ui_MainWindow as UI_Page3

csvfile1='aac1.csv'
csvfile2='aac2.csv'
csvfile3='aac3.csv'

def picButton(image_path):
        #image_path = "path_to_your_image.jpg"
        image = QImage(image_path)
        # Resize the image to fit the button
        resized_image = image.scaled(190, 140)
        # Create a pixmap from the resized image
        pixmap = QPixmap.fromImage(resized_image)
        # Set the pixmap as the button's icon
        button.setIcon(pixmap)
        button.setIconSize(pixmap.size())

def qreadcsv(csvfile):
    wavs=[]
    image_names=[]
    words=[]
    
    with open(csvfile, 'r', encoding='utf-8') as file:
        reader = csv.reader(file)
        for csvrow in reader:
            image_name = csvrow[1]
            image_names.append(image_name)
            wav = csvrow[2]
            wavs.append(wav)
            word=csvrow[3]
            words.append(word)
    #print(wavs)
    #print(image_names)
    #print(words)
    return image_names,wavs,words
    
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.stacked_widget = QStackedWidget()
        self.setCentralWidget(self.stacked_widget)
        # Resize the window to 1280x980
        self.resize(1280, 980)
        # Create the pages
        
        
        self.page1 = Page1()
        self.page2 = Page2()
        self.page3 = Page3()
        self.stacked_widget.addWidget(self.page1)
        self.stacked_widget.addWidget(self.page2)
        self.stacked_widget.addWidget(self.page3)
        #self.shared_parameter = []
        self.page1.ui.p2Button.clicked.connect(self.switch_to_page2)
        self.page1.ui.p3Button.clicked.connect(self.switch_to_page3)
        self.page2.ui.p1Button.clicked.connect(self.switch_to_page1)
        self.page2.ui.p3Button.clicked.connect(self.switch_to_page3)
        self.page3.ui.p1Button.clicked.connect(self.switch_to_page1)
        self.page3.ui.p2Button.clicked.connect(self.switch_to_page2)
        #self.page1.parameter_changed.connect(self.update_parameter)
        #self.page2.parameter_changed.connect(self.update_parameter)
        #self.page3.parameter_changed.connect(self.update_parameter)
          
    def switch_to_page1(self):
        self.stacked_widget.setCurrentWidget(self.page1)
    def switch_to_page2(self):
        self.stacked_widget.setCurrentWidget(self.page2)
    def switch_to_page3(self):
        self.stacked_widget.setCurrentWidget(self.page3)    
    
    
    
    #def update_parameter(self, value):
        #self.shared_parameter = value
    
class Page1(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = UI_Page1()
        self.ui.setupUi(self)
        self.picpath='pic'
        self.wavpath='wav'
        csvfile=csvfile1
        self.ui.actionwave_Directory.triggered.connect(self.readcsv)
        self.ui.actionHelp.triggered.connect(self.showhelp)
        self.ui.actionAbout.triggered.connect(self.showAbout)
        
        self.image_names,self.wavs,self.words = qreadcsv(csvfile)
        self.button_names = [
            self.ui.Button_1, self.ui.Button_2, self.ui.Button_3, self.ui.Button_4,
            self.ui.Button_5, self.ui.Button_6, self.ui.Button_7, self.ui.Button_8,
            self.ui.Button_9, self.ui.Button_10, self.ui.Button_11, self.ui.Button_12,
            self.ui.Button_13, self.ui.Button_14, self.ui.Button_15, self.ui.Button_16,
            self.ui.Button_17, self.ui.Button_18, self.ui.Button_19, self.ui.Button_20,
            self.ui.Button_21, self.ui.Button_22, self.ui.Button_23, self.ui.Button_24
        ]
        for button in self.button_names:
            self.showpic(button)
            button.clicked.connect(self.button_clicked)
        
        self.buttonbuf = []
        self.showword = []
        self.ui.clearButton.clicked.connect(self.clear)    
        self.ui.playButton.clicked.connect(self.playall)
    
    def clear(self):
        self.buttonbuf = []
        self.showword = []
        self.ui.label.setText('')
     
    def showpic(self, button):
        self.button_index = self.button_names.index(button)  # Get the index of the button
        image_name = self.image_names[self.button_index]
        self.image_name = "%s/%s" % (self.picpath,str(image_name))
        #print(self.image_name)
        image = QtGui.QImage(self.image_name)
        # Resize the image to fit the button
        resized_image = image.scaled(200, 140)
        # Create a pixmap from the resized image self.Button_1.setIcon(QtGui.QIcon(self.pic1))
        pixmap = QtGui.QPixmap.fromImage(resized_image)
        # Set the pixmap as the button's icon
        button.setIcon(QtGui.QIcon(pixmap))
        button.setIconSize(pixmap.size())
    
    def playwav(self,wavname):
        wavf = "%s/%s" % (self.wavpath,str(wavname))
        #print(wavf)
        try: 
            data, fs = sf.read(wavf, dtype='int16')  
            sd.play(data, fs)
            sd.wait()
        except:
            print("Error, the formate of wav file should be mono channel and 22.05K sampling rate.")
        
    def button_clicked(self):
        button = self.sender()  # Get the button that was clicked
        self.button_index = self.button_names.index(button)  # Get the index of the button
        word=self.words[self.button_index]
        self.showword.append(word)
        wstring = ''.join(self.showword)
        self.buttonbuf.append(self.button_index)
        self.ui.label.setText(wstring)
        wavname=self.wavs[self.button_index]
        self.playwav(wavname)
     
    def playall(self):
        #print(self.buttonbuf)
        for indx in self.buttonbuf:
            wavname=self.wavs[indx]
            self.playwav(wavname)
            sd.wait()
    def showhelp(self): 
        QMessageBox.information(None, 'Welcome!', "1.可使用已經編好的三個csv檔，\n2.檢查喇叭音量\n 3.可於[設定]另行設置別的csv檔或是自行修改原csv檔，格式請參照原附檔\n4.除非檔案中無中文字，否則請勿使用excel程式編寫csv檔")

    def showAbout(self):
        QMessageBox.information(None,'開發','此程式為國立高雄師範大學 聽語研究所 鄭靜宜教授開發，\n 敬請指教，jengyi12345@gmail.com')   
        
    def readcsv(self):
        self.clear()
        filename, filter = QFileDialog.getOpenFileName(self, '開啟csv檔案', 
            './', 'CSV files (*.csv)')
        if filename:
            csvfile= filename
            self.image_names,self.wavs,self.words = qreadcsv(csvfile)
            self.button_names = [
            self.ui.Button_1, self.ui.Button_2, self.ui.Button_3, self.ui.Button_4,
            self.ui.Button_5, self.ui.Button_6, self.ui.Button_7, self.ui.Button_8,
            self.ui.Button_9, self.ui.Button_10, self.ui.Button_11, self.ui.Button_12,
            self.ui.Button_13, self.ui.Button_14, self.ui.Button_15, self.ui.Button_16,
            self.ui.Button_17, self.ui.Button_18, self.ui.Button_19, self.ui.Button_20,
            self.ui.Button_21, self.ui.Button_22, self.ui.Button_23, self.ui.Button_24
            ]
            for button in self.button_names:
                self.showpic(button)
                
        else:
            csvfile= "aacp1.csv"
            pass
            
    
            
class Page2(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = UI_Page2()
        self.ui.setupUi(self)
        self.picpath='pic'
        self.wavpath='wav'
        csvfile=csvfile2
        
        self.ui.actionwave_Directory.triggered.connect(self.readcsv)
        self.ui.actionHelp.triggered.connect(self.showhelp)
        self.ui.actionAbout.triggered.connect(self.showAbout)
        
        self.image_names,self.wavs,self.words = qreadcsv(csvfile)
        self.button_names = [
            self.ui.Button_1, self.ui.Button_2, self.ui.Button_3, self.ui.Button_4,
            self.ui.Button_5, self.ui.Button_6, self.ui.Button_7, self.ui.Button_8,
            self.ui.Button_9, self.ui.Button_10, self.ui.Button_11, self.ui.Button_12,
            self.ui.Button_13, self.ui.Button_14, self.ui.Button_15, self.ui.Button_16,
            self.ui.Button_17, self.ui.Button_18, self.ui.Button_19, self.ui.Button_20,
            self.ui.Button_21, self.ui.Button_22, self.ui.Button_23, self.ui.Button_24
        ]
        for button in self.button_names:
            self.showpic(button)
            button.clicked.connect(self.button_clicked)
        
        self.buttonbuf = []
        self.showword = []
        self.ui.clearButton.clicked.connect(self.clear)    
        self.ui.playButton.clicked.connect(self.playall)
    
    def clear(self):
        self.buttonbuf = []
        self.showword = []
        self.ui.label.setText('')
     
    def showpic(self, button):
        self.button_index = self.button_names.index(button)  # Get the index of the button
        image_name = self.image_names[self.button_index]
        self.image_name = "%s/%s" % (self.picpath,str(image_name))
        #print(self.image_name)
        image = QtGui.QImage(self.image_name)
        # Resize the image to fit the button
        resized_image = image.scaled(200, 140)
        # Create a pixmap from the resized image self.Button_1.setIcon(QtGui.QIcon(self.pic1))
        pixmap = QtGui.QPixmap.fromImage(resized_image)
        # Set the pixmap as the button's icon
        button.setIcon(QtGui.QIcon(pixmap))
        button.setIconSize(pixmap.size())
    
    def playwav(self,wavname):
        wavf = "%s/%s" % (self.wavpath,str(wavname))
        #print(wavf)
        try: 
            data, fs = sf.read(wavf, dtype='int16')  
            sd.play(data, fs)
            sd.wait()
        except:
            print("Error, the formate of wav file should be mono channel and 22.05K sampling rate.")
        
    def button_clicked(self):
        button = self.sender()  # Get the button that was clicked
        self.button_index = self.button_names.index(button)  # Get the index of the button
        word=self.words[self.button_index]
        self.showword.append(word)
        wstring = ''.join(self.showword)
        self.buttonbuf.append(self.button_index)
        self.ui.label.setText(wstring)
        wavname=self.wavs[self.button_index]
        self.playwav(wavname)
     
    def playall(self):
        #print(self.buttonbuf)
        for indx in self.buttonbuf:
            wavname=self.wavs[indx]
            self.playwav(wavname)
            sd.wait()
    def showhelp(self): 
        QMessageBox.information(None, 'Welcome!', "1.可使用已經編好的三個csv檔，\n2.檢查喇叭音量\n 3.可於[設定]另行設置別的csv檔或是自行修改原csv檔，格式請參照原附檔\n4.除非檔案中無中文字，否則請勿使用excel程式編寫csv檔")

    def showAbout(self):
        QMessageBox.information(None,'開發','此程式為國立高雄師範大學 聽語研究所 鄭靜宜教授開發，\n 敬請指教，jengyi12345@gmail.com')   
        
    def readcsv(self):
        self.clear()
        filename, filter = QFileDialog.getOpenFileName(self, '開啟csv檔案', 
            './', 'CSV files (*.csv)')
        if filename:
            csvfile= filename
            self.image_names,self.wavs,self.words = qreadcsv(csvfile)
            self.button_names = [
            self.ui.Button_1, self.ui.Button_2, self.ui.Button_3, self.ui.Button_4,
            self.ui.Button_5, self.ui.Button_6, self.ui.Button_7, self.ui.Button_8,
            self.ui.Button_9, self.ui.Button_10, self.ui.Button_11, self.ui.Button_12,
            self.ui.Button_13, self.ui.Button_14, self.ui.Button_15, self.ui.Button_16,
            self.ui.Button_17, self.ui.Button_18, self.ui.Button_19, self.ui.Button_20,
            self.ui.Button_21, self.ui.Button_22, self.ui.Button_23, self.ui.Button_24
            ]
            for button in self.button_names:
                self.showpic(button)
                
        else:
            csvfile= "aacp2.csv"
            pass
            
class Page3(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = UI_Page3()
        self.ui.setupUi(self)
        self.picpath='pic'
        self.wavpath='wav'
        csvfile=csvfile3
        self.ui.actionwave_Directory.triggered.connect(self.readcsv)
        self.ui.actionHelp.triggered.connect(self.showhelp)
        self.ui.actionAbout.triggered.connect(self.showAbout)
        
        self.image_names,self.wavs,self.words = qreadcsv(csvfile)
        self.button_names = [
            self.ui.Button_1, self.ui.Button_2, self.ui.Button_3, self.ui.Button_4,
            self.ui.Button_5, self.ui.Button_6, self.ui.Button_7, self.ui.Button_8,
            self.ui.Button_9, self.ui.Button_10, self.ui.Button_11, self.ui.Button_12,
            self.ui.Button_13, self.ui.Button_14, self.ui.Button_15, self.ui.Button_16,
            self.ui.Button_17, self.ui.Button_18, self.ui.Button_19, self.ui.Button_20,
            self.ui.Button_21, self.ui.Button_22, self.ui.Button_23, self.ui.Button_24
        ]
        for button in self.button_names:
            self.showpic(button)
            button.clicked.connect(self.button_clicked)
        
        self.buttonbuf = []
        self.showword = []
        self.ui.clearButton.clicked.connect(self.clear)    
        self.ui.playButton.clicked.connect(self.playall)
    
    def readcsv(self):
        self.clear()
        filename, filter = QFileDialog.getOpenFileName(self, '開啟csv檔案', 
            './', 'CSV files (*.csv)')
        if filename:
            csvfile= filename
            self.image_names,self.wavs,self.words = qreadcsv(csvfile)
            self.button_names = [
            self.ui.Button_1, self.ui.Button_2, self.ui.Button_3, self.ui.Button_4,
            self.ui.Button_5, self.ui.Button_6, self.ui.Button_7, self.ui.Button_8,
            self.ui.Button_9, self.ui.Button_10, self.ui.Button_11, self.ui.Button_12,
            self.ui.Button_13, self.ui.Button_14, self.ui.Button_15, self.ui.Button_16,
            self.ui.Button_17, self.ui.Button_18, self.ui.Button_19, self.ui.Button_20,
            self.ui.Button_21, self.ui.Button_22, self.ui.Button_23, self.ui.Button_24
            ]
            for button in self.button_names:
                self.showpic(button)
                
        else:
            csvfile= "aacp3.csv"
            pass
        
    def clear(self):
        self.buttonbuf = []
        self.showword = []
        self.ui.label.setText('')
     
    def showpic(self, button):
        self.button_index = self.button_names.index(button)  # Get the index of the button
        image_name = self.image_names[self.button_index]
        self.image_name = "%s/%s" % (self.picpath,str(image_name))
        #print(self.image_name)
        image = QtGui.QImage(self.image_name)
        # Resize the image to fit the button
        resized_image = image.scaled(200, 140)
        # Create a pixmap from the resized image self.Button_1.setIcon(QtGui.QIcon(self.pic1))
        pixmap = QtGui.QPixmap.fromImage(resized_image)
        # Set the pixmap as the button's icon
        button.setIcon(QtGui.QIcon(pixmap))
        button.setIconSize(pixmap.size())
    
    def playwav(self,wavname):
        wavf = "%s/%s" % (self.wavpath,str(wavname))
        #print(wavf)
        try: 
            data, fs = sf.read(wavf, dtype='int16')  
            sd.play(data, fs)
            sd.wait()
        except:
            print("Error, the formate of wav file should be mono channel and 22.05K sampling rate.")
        
    def button_clicked(self):
        button = self.sender()  # Get the button that was clicked
        self.button_index = self.button_names.index(button)  # Get the index of the button
        word=self.words[self.button_index]
        self.showword.append(word)
        wstring = ''.join(self.showword)
        self.buttonbuf.append(self.button_index)
        self.ui.label.setText(wstring)
        wavname=self.wavs[self.button_index]
        self.playwav(wavname)
     
    def playall(self):
        print(self.buttonbuf)
        for indx in self.buttonbuf:
            wavname=self.wavs[indx]
            self.playwav(wavname)
            sd.wait()   
    def showhelp(self): 
        QMessageBox.information(None, 'Welcome!', "1.可使用已經編好的三個csv檔，\n2.檢查喇叭音量\n 3.可於[設定]另行設置別的csv檔或是自行修改原csv檔，格式請參照原附檔\n4.除非檔案中無中文字，否則請勿使用excel程式編寫csv檔")

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

