import os
import wave
import struct
from datetime import datetime

import pvporcupine
from pvrecorder import PvRecorder

keyword_paths=['/home/dfr84/Python/JARVIS/Jarvis_en_linux_v4_0_0.ppn']
output_path = "/home/dfr84/Python/JARVIS/output.wav"

def main():
    porcupine = pvporcupine.create(access_key='Iy02++yL2aOfXc9mmvSWAfdhVSR8PEtMjWMIWRbaC4bXno57SgoI8A==', keyword_paths=['/home/dfr84/Python/JARVIS/Jarvis_en_linux_v4_0_0.ppn'])

    print('PORCUPINE VISION: %s' % porcupine.version)

    for i, device in enumerate(PvRecorder.get_available_devices()):
        print('DEVICE %d: %s' % (i, device))

    keywords = list()
    for x in keyword_paths:
        keyword_phrase_part = os.path.basename(x).replace('.ppn', '').split('_')
        if len(keyword_phrase_part) > 6:
            keywords.append(' '.join(keyword_phrase_part[0:-6]))
        else:
            keywords.append(keyword_phrase_part[0])

    recorder = PvRecorder(
    frame_length=porcupine.frame_length,
    device_index=4)
    
    recorder.start()        

    wav_file = None
    wav_file = wave.open(output_path, "w")
    wav_file.setnchannels(1)
    wav_file.setsampwidth(2)
    wav_file.setframerate(16000)

    print('LISTENING... (PRESS CTRL+C TO EXIT)')     

    try:
        while True:
            pcm = recorder.read()
            result = porcupine.process(pcm)

            if wav_file is not None:
                wav_file.writeframes(struct.pack("h" * len(pcm), *pcm))

            if result >= 0:
                print('[%s] DETECTED %s' % (str(datetime.now()), keywords[result]))
    
    except KeyboardInterrupt:
        print('STOPPING...')
    
    finally:
        recorder.delete()
        porcupine.delete()
        
        if wav_file is not None:
            wav_file.close()

if __name__ == '__main__':
    main()