import click
import chalk
import yaml
import apiai
import config
import json
from forex_python.converter import CurrencyRates, CurrencyCodes
import time
import datetime

from config import config_file_paths
from util import *

CLIENT_ACCESS_TOKEN = os.environ.get('API_AI_TOKEN', config.API_AI_TOKEN)
ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)
request = ai.text_request()
request.session_id = os.environ.get('API_AI_SESSION_ID', config.API_AI_SESSION_ID)

# config file path
MONEY_CONFIG_FILE_PATH = config_file_paths['MONEY_CONFIG_FILE_PATH']
MONEY_CONFIG_FOLDER_PATH = get_folder_path_from_file_path(MONEY_CONFIG_FILE_PATH)

# currency converter
currency_rates = CurrencyRates()
currency_codes = CurrencyCodes()

# check status of setup
def status():
    if os.path.isfile(MONEY_CONFIG_FILE_PATH):
        with open(MONEY_CONFIG_FILE_PATH, 'r') as config_file:
            contents = yaml.load(config_file)
            click.echo(contents)
    else:
        click.echo('The configuration file for this module does not exist. Please type "dude money setup" to create a new one')

# create new setup config
def setup():
    create_folder(MONEY_CONFIG_FOLDER_PATH)

    if ask_overwrite(MONEY_CONFIG_FILE_PATH):
        return

    chalk.blue('Enter default currency code:')
    currency_code = (raw_input().strip())
    click.echo(currency_rates.get_rates(currency_code))
    click.echo(currency_codes.get_symbol(currency_code))
    click.echo(currency_codes.get_currency_name(currency_code))

    chalk.blue('Enter inital amount:')
    initial_money = int(raw_input().strip())

    setup_data = dict (
        currency_code = currency_code,
        initial_money = initial_money
    )

    input_data(setup_data, MONEY_CONFIG_FILE_PATH)

def expense():
    create_folder(MONEY_CONFIG_FOLDER_PATH)
    with open(MONEY_CONFIG_FOLDER_PATH + '/expenditures.txt', 'a') as fp:
        request.query = raw_input()
        click.echo('output: ')
        response = request.getresponse().read()
        output = json.loads(response)
        # click.echo(output)
        currency_name = output['result']['parameters']['currency-name']
        item = output['result']['parameters']['any']
        number = output['result']['parameters']['number']

        timestamp = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')
        fp.write('{} {} {} {}\n'.format(timestamp, currency_name, number, item))

# command checker
def check_sub_command(c):
    sub_commands = {
        'status' : status,
        'setup' : setup,
        'exp' : expense
    }
    try:
        return sub_commands[c]()
    except KeyError:
        chalk.red('Command does not exist!')
        click.echo('Try "dude money --help" for more info')

# the main process
def process(input):
    input = input.lower().strip()
    check_sub_command(input)

@@ -161,16 +161,29 @@
 datetime
+%0Aimport shlex
 %0A%0Afrom c
@@ -2179,17 +2179,133 @@
 %5D%5B'any'%5D
+ if len(output%5B'result'%5D%5B'parameters'%5D%5B'any'%5D.split()) == 1 else ('%22' + output%5B'result'%5D%5B'parameters'%5D%5B'any'%5D + '%22')
 %0A
-
         
@@ -2532,16 +2532,351 @@
 item))%0A%0A
+def expenses():%0A    with open(MONEY_CONFIG_FOLDER_PATH + '/expenditures.txt') as fp:%0A        for line in fp.read().split('%5Cn'):%0A            if len(line) == 0: continue%0A            (date, time, currency_name, number, item) = shlex.split(line)%0A            click.echo(date + ' ' + time + ' ' + currency_name + ' ' + number + ' ' + item)%0A%0A
 # comman
@@ -2984,16 +2984,16 @@
  setup,%0A
-
         
@@ -3007,16 +3007,43 @@
  expense
+,%0A        'exps' : expenses
 %0A    %7D%0A 

check expenses - money module