import os
from elasticsearch import Elasticsearch
from elasticsearch.helpers import bulk

"""
Open application using voice
- To list apps in applications:
    - d = '/Applications'
    - apps = list(map(lambda x: x.split('.app')[0], os.listdir(d)))
"""

def openApp(app_name):
    os.system(f"open {app_name}.app")

s
def mapCommands():
    d = '/Applications'
    records = []
    apps = os.listdir(d)
    for app in apps:
        record = {}
        record['voice_command'] = 'open ' + app.split('.app')[0]
        record['sys_command'] = 'open ' + d +'/%s' %app.replace(' ','\ ')
        records.append(record)

"""
Elasticsearch 
"""
def create_index(records):
    """ Now your data is all searchable in the index voice_assistant
    Description:
    The response variable we get back from the search function below is generated by:
        - the language elastic uses referred to as Query DSL. 
    We’re basically doing a simple TF-IDF search on the voice command with some fuzziness 
        — to account for misspellings/bad transcriptions
    """
    es = Elasticsearch(['localhost:9200'])
    bulk(es, records, index='voice_assistant', doc_type='text', raise_on_error=True)


def search_es(query):
    res = es.search(index="voice_assistant", doc_type="text", body={                     
    "query" :{
        "match": {
            "voice_command": {
                "query": query,
                "fuzziness": 2
            }
            }
        },
    })
    return res['hits']['hits'][0]['_source']['sys_command']



