from threading import Thread, Lock
import time
from Queue import Queue
import datetime
import os
from subprocess import Popen

from google.cloud import speech
from google.cloud.speech import enums
from google.cloud.speech import types

rootDir = '/media/alek/Elements/GoogleDrive/Lawyer Requested Folder'
ext = [".flac"]
tLock = Lock()

def Main():
    q = Queue(maxsize=0)
    num_threads = 10

    for i in range(num_threads):
        worker = Thread(target=task, args =(q,))
        worker.setDaemon(True)
        worker.start()


    for path, subdirList, fileList in os.walk(rootDir):
        for fname in fileList:
            if fname.endswith(tuple(ext)):
                # combine filepath and filename
                complete_filename = os.path.join(path, fname)
                q.put(complete_filename)
    q.join()

def task(q):
    while True:
        # upload flac to gcs
        fullpath = q.get()
        path, fname = os.path.split(fullpath)
        gcs_uri = "gs://uci-video/" + fname
        transcript = transcribe(gcs_uri)
        tLock.aquire()
        open_text_file = prepareTextFile(fullpath)
        writeTranscript(transcript, open_text_file)
        open_text_file.close()
        tLock.release()
        q.task_done()

# [START def_transcribe_gcs]
def transcribe(gcs_uri):
    """Transcribe the given audio file asynchronously and output the word time
    offsets."""
    client = speech.SpeechClient()

    audio = types.RecognitionAudio(uri=gcs_uri)
    config = types.RecognitionConfig(
        encoding=enums.RecognitionConfig.AudioEncoding.FLAC,
        sample_rate_hertz=16000,
        language_code=gcs_uri[-10:-5],
        enable_word_time_offsets=True)

    operation = client.long_running_recognize(config, audio)
    return operation.result(timeout=None)

def writeTranscript(result, open_text_file):
    for results in result.results:
        alternatives = results.alternatives
        for alternative in alternatives:
            for count, word_info in enumerate(alternative.words, 1):
                word = word_info.word
                start_time = word_info.start_time
                if count % 15 == 0:
                    tofile = "\n" + str(datetime.timedelta(seconds=start_time.seconds)) + ' ' + word + ' '
                else:
                    tofile = word + " "
                open_text_file.write(tofile)

def prepareTextFile(complete_fpath):
    # create textfile to write and add metadata
    path, fname = os.path.split(complete_fpath)
    textfilename = fname[:-4] + "txt"
    open_text_file = open(textfilename, 'w')
    open_text_file.write("File: " + fname[:-11] + "\n")
    open_text_file.write("Path: " + path + "\n")
    open_text_file.write('0:00:00   ')
    return open_text_file

def upload_to_GS_bucket(fname):
    p = Popen(["gsutil", "cp", fname, "gs://uci-video"])
    while Popen.poll(p) is None:
        time.sleep(0.1)
    p.wait()
    return "gs://uci-video/" + fname


if __name__ == "__main__":
    Main()