import os
import time

import wave
import pyaudio
import threading

from config import cfg


CHUNK = 1024  # frame count in buffer



class __player():
    def __init__(self):
        self.isplaying = False
        self.forcestop = False
           

    def Play(self, filepath):
        if self.isplaying:
            return False
        self.isplaying = True
            
        pa = pyaudio.PyAudio()
        try:
            wf = wave.open(filepath, 'rb')
        except Exception as e:
            print(e)
            pa.terminate()
            self.isplaying = False
            return False
            
        try:
            stream = pa.open(format=pa.get_format_from_width(wf.getsampwidth()),
                    channels=wf.getnchannels(),
                    rate=wf.getframerate(),
                    output=True)
        except Exception as e:
            print(e)
            wf.close()
            pa.terminate()
            self.isplaying = False
            return False

        data = wf.readframes(CHUNK)
        while len(data) > 0:
            stream.write(data)
            data = wf.readframes(CHUNK)
            if self.forcestop:
               break

        stream.stop_stream()
        stream.close()
        wf.close()
        pa.terminate()
        self.isplaying = False
        self.forcestop = False
        return True

    
    def AsynPlay(self, filepath):
        if self.isplaying:
            return False
            
        thread = threading.Thread(target = self.Play, args = (filepath,))
        thread.start()
        return True
        
    
    def ForceStop(self):
        if self.isplaying:
            self.forcestop = True
            while(self.isplaying):
                time.sleep(1)
            return True
        else:
            return False
            

Player =  __player()

        
