#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 16 11:39:35 2019
@author: shrinidhikr
"""
import speech_recognition as sr
import cv2
#import firebase_con as fb
#import os
import numpy as np
def database_con(write_data,name,obs):
    
    file = open(name+".txt","w")
    file.writelines(write_data)
    file.write("\n"+"Observations during diagnosis"+"\n")
    file.writelines(obs)
    fname = file.name
    file.close()
#    db_ = {"patient_name":name,"file_f":fname}
#    fb.calldb(db_)
    #if os.path.exists(fname):
    #    os.remove(fname)

def procedure_data():
    
    procedure_set = {}
    with open("D:/.spyder-py3/endoprocess.txt","r") as f:
        proc_data = f.read().split("\n")
    for line in proc_data:
        procedure_set[line.lower()]=False
    #print(procedure_set)
    return procedure_set

def myCommand():
    
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Hello Doctor!")
        r.adjust_for_ambient_noise(source, duration=1)
        audio = r.listen(source)
    try:
        command = r.recognize_google(audio,language="en-in")
        print("You said: " + command)
    except sr.UnknownValueError:
        print("Could not caputre that! Try again....")
        command = myCommand()
    return command

def assistant(dataset_,command,write_to_db,observations):
    
    if "stop" in command.lower():
        return False
    
    if command in dataset_:
        if dataset_.get(command)==False:
            dataset_[command] = True
            write_to_db.append(command+"\n")
    if "click" in command.lower():
        Capture=True
        video = cv2.VideoCapture(0)
        while True:
            
            check,frame = video.read()
            if(Capture):
                cv2.imwrite("D:/.spyder-py3/Image"+str(np.random.randint(0,10))+".png",frame)
                print("wtf")
                Capture=False
                #a=a+1
                
                break
        video.release()
        cv2.destroyAllWindows()
    if "note" in command.lower():
        print("What is to be noted?")
        log = myCommand()
        #This has to be sent to database 
        observations.append(log)
        print(log)
        
#    write_to_db.append("DUMMY COMMAND "+command+"\n")
    return True

#if __name__ == "__main__":

def app_run():
    #Counter For Image

    write_to_db = []
    observations = []
    observations.append("Normal")
    dataset_ = procedure_data()
    print("Say patient name")
    patient_name = myCommand()
    voice = True
    #write_to_db.append("Hello")
    #database_con(write_to_db,patient_name)
    while voice:
        voice = assistant(dataset_,myCommand(),write_to_db,observations)
    database_con(write_to_db,patient_name,observations)
#global a
app_run()
