import sys
import pytz
import time
import calendar
import ConfigParser
import cmd
from datetime import date, datetime, timedelta
from strategy import strategy
from exchange import cb_exchange_sim, cb_exchange

class runner(cmd.Cmd):

    def __init__(self):
        """Create a new runner with provided CLI commands. Default commands are:
        \n1. exit: quit autotrader
        \n2. help: display all commands
        \n3. price: display the most recent bitcoin price
        \n4. run: start trading on live data
        \n5. backtest: run a backtest on historic data
        \n6. load: load a new strategy
        """

        print("    __    _ __             _     __         ")
        print("   / /_  (_) /__________ _(_)___/ /__  _____")
        print("  / __ \/ / __/ ___/ __ `/ / __  / _ \/ ___/")
        print(" / /_/ / / /_/ /  / /_/ / / /_/ /  __/ /    ")
        print("/_.___/_/\__/_/   \__,_/_/\__,_/\___/_/     ")
        print("")
        print("Welcome to bitraider v0.0.4, an algorithmic Bitcoin trader!")

        cmd.Cmd.__init__(self)
        self.prompt = '> '
        self.intro = "Type a command to get started or type \'help\'"


        # Init config
        self.config_path = "settings.ini"
        self.config = ConfigParser.ConfigParser()
        try:
            self.config.read(self.config_path)
        except Exception, err:
            print(str(err))

        # Set up strategy
        self.strategies = {}
        """The currently loaded strategies"""

        # Try to load a default strategy, if one exists
        try:
            default_strategy_module = self.config.get("default_strategy", "module")
            default_strategy_class = self.config.get("default_strategy", "class")
            self.load_strategy(default_strategy_module, default_strategy_class)
        except Exception, err:
            #print(str(err))
            print("No default strategy configured. Run "
                    "\'config default\' to set one")
            try:
                self.config.add_section("default_strategy")
            except:
                pass

        self.exchange = cb_exchange_sim(1000, 1)
        self.accounts = None

        # Get auth credentials from settings.ini, if they exist, authorize
        try:
            self.auth_key = self.config.get("auth", "key")
            self.auth_secret = self.config.get("auth", "secret")
            self.auth_password = self.config.get("auth", "password")
            self.authenticate()
        except Exception, err:
            #print(str(err))
            print("No authentication configured. Run "
                    "\'config auth\' to set it")
            try:
                self.config.add_section("auth")
            except:
                pass

        if self.accounts is not None:
            print(str(len(self.accounts))+" accounts were found.")
            for i in range(0, len(self.accounts)):
                try:
                    print("Account ID: "+str(self.accounts[i]['id'])+" Available Funds: "+str(self.accounts[i]['available'])+" "+str(self.accounts[i]['currency'])+"")
                except Exception, err:
                    print("Something went wrong while trying to authenticate with the provided credentials. Try running config>auth again.")

    def do_exit(self, line):