#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#先在intell.csv設定音檔和選項，在intellwav檔案夾中放相應音檔，檢查或清空intell.txt記錄檔(將附加資料)
#先設定要播放之音檔的格式 int16 or float32 (line117), or fs = 22050
#pyinstaller -F --icon=intell.ico jintell.py

import random
import tkinter
from tkinter import *
import tkinter.font as font
from tkinter import messagebox
import sounddevice as sd
import soundfile as sf
import pandas

fs = 22050
BACKGROUND_COLOR = "#8290c4"
FOREGROUND_COLOR = "black"
current_card={}
to_show={}
itemno=0
showno=0
intell_score=0
wavpath='intellwav'
wavfilename=''
respfile='intell.txt'
subno = "000"
print("Please input the subject number: ")
subno = input()
if subno == '': subno = "000"
print("The subject number is : " + subno + '. The task will begin.')
input("Press Enter to continue...")
f = open(respfile, 'a')
lines = ['intell_subno: ',str(subno), '\n']
f.writelines(lines)
f.close()

window= Tk()
myFont1 = font.Font(family = "標楷體",size=14)
#myFont2 = font.Font(family='文鼎標楷注音',size=24) #設定字型
myFont2 = font.Font(family = "標楷體",size = 28,weight = "bold")

window.title("清晰度判斷")
swidth = window.winfo_screenwidth()-10
sheight = window.winfo_screenheight()-10
print("Screen width:", swidth)
print("Screen height:", sheight)

window.geometry(f'{swidth}x{sheight}')
window.config(padx=50, pady=50, bg = BACKGROUND_COLOR)
window.resizable(False,False) #Make window non-resizable, optimal view

mycanvas= Canvas(width=30, height=20)
mycanvas.place(x=swidth-100, y=0) # put itemno place

fram1= Frame(window, relief=RAISED,borderwidth=3, bg = '#f5beb0')
fram1.place(x=50, y=100) # put scale place

def show_value_h1(value):
    global intell_score
    intell_score=var_h1.get()
    label_h1.set(intell_score)
    
Label(fram1, text='不清楚', font= myFont1).pack(side=LEFT)
var_h1=IntVar()        
scale_h1=Scale(fram1,variable=var_h1,orient="horizontal",width=30,length=swidth/1.4,command=show_value_h1)   
scale_h1.pack(side=LEFT, padx=30, pady=50)
label_h1=StringVar()
Label(fram1, textvariable=label_h1, font= myFont1).pack(side=BOTTOM)
Label(fram1, text='清楚', font= myFont1).pack(side=RIGHT)

word='先按[聽下一題] 聽題目，之後可拖動滑動條決定所聽到語音的清晰度分數(數字愈大代表愈清楚)，或輸入文字，然後按[確定]存資料。'
label = Label(window, text=str(word), font= myFont1)
label.place(x=50, y=0)

fram2= Frame(window, relief=RAISED,borderwidth=3, bg = '#f5beb0')
fram2.place(x=50, y=sheight/2) # put myentry place
label_text = Label(fram2, text = '聽寫(國字或注音):',font= myFont1)
label_text.pack(side=LEFT,padx=3,pady=50)

myentry = Entry(fram2, bd =4,font= myFont1, width = 80 )
myentry.pack(padx=25, pady=50)
#myentry.insert(-1, '2')
showno_text=mycanvas.create_text(10,10, text=str(showno), font=("Ariel", 14), width = 10)

try:
    data=pandas.read_csv("intell.csv")
except FileNotFoundError:
    original_data= pandas.read_csv("intell.csv")
    #print(original_data)
    to_show=original_data.to_dict(orient="records")
    total_num=len(to_show)
else:
    to_show=data.to_dict(orient="records")
    total_num=len(to_show)
      
def nextsti():
    global current_card,itemno,showno,card_word,total_num,wavfilename, choose1,choose2,choose3,choose4
    myentry.delete(0, END)
    showno += 1
    current_card= random.choice(to_show) #random items from list to show
    print(current_card)
    
    itemno=current_card["itemno"]
    wavfilename=current_card["wavfile"]
    playsti()
    mycanvas.itemconfig(showno_text, text=str(showno))
    showchoice()
    if len(to_show) >= 2:
        to_show.remove(current_card)
        data=pandas.DataFrame(to_show)
        print(len(to_show))        
    else:
        next_button["state"] = DISABLED
   
def playsti():
    global wavfilename
    data2, fs = sf.read(wavpath+'/'+wavfilename, dtype='int16')#設定音檔格式 int16 or float32
    sd.play(data2, fs)
    sd.wait()

def showchoice(): 
    global choose1, choose1_button
    choose1_button = Button(window,text='確定',font= myFont2,highlightthickness=3,bg = "#9ce9f0", command=resp1) 
    choose1_button.place(x=swidth-350, y=sheight-550, width=200, height=140)
      
def resp1():
    global  choose1_button,respfile,itemno, intell_score
    subinput = str(myentry.get())
    choose1_button.destroy()
    f = open(respfile, 'a')
    lines = [str(itemno),',', str(intell_score),',',subinput,'\n']
    f.writelines(lines)
    f.close()
    if next_button["state"] == DISABLED:
        messagebox.showinfo('The end', '清晰度評估完畢，請檢視記錄檔!')

next_button = Button(window,text='聽下一題',highlightthickness= 4,bg = "#d8f5b0", command=nextsti) 
next_button['font'] = myFont2
next_button.place(x=swidth-350, y=sheight-350, width=200, height=150)

window.mainloop()