#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
ib-downloader4.py

Created on Tue Jul  5 15:53:45 2016

@author: nwillemse

"""
import time
import argparse
import pandas as pd

from datetime import datetime
from ib.ext.Contract import Contract
from ib.opt import Connection


class Downloader:
    def __init__(
        self, tickers, exchange, ticker_type, expiry, barsize,
        start_date, end_date, ib_client_id, ib_port
    ):
        self.tickers = tickers
        self.exchange = exchange
        self.ticker_type = ticker_type
        self.expiry = expiry
        self.barsize = barsize
        self.client_id = ib_client_id
        self.order_id = 1
        self.port = ib_port
        self.currency = 'USD'
        self.tws_conn = None
        self.curr_ohlc = pd.DataFrame(
            columns=['open', 'high', 'low', 'close', 'volume', 'open_interest']
        )
        self.no_data_error = False
        self.got_hist_data = False
        self.dates_list = self._get_trade_dates(start_date, end_date)
        self.what_to_show = 'MIDPOINT' if ticker_type=='CASH' else 'TRADES'
        self.end_date = end_date


    def _get_trade_dates(self, start_dt=None, end_dt=None):
        if self.ticker_type in ['CASH', 'FUT']:
            dates = pd.date_range(start_dt, end_dt).tolist()
            res = sorted(map(lambda x: x.strftime('%Y-%m-%d %H:%M:%S'), dates), reverse=True)
#            res.sort(reverse=True)
            print(res)
        else:
            fn = 'nyse_dates.txt'
            print("Loading trading days from %s..." % fn)
            a = pd.read_csv(fn, parse_dates=['trade_date'])
            sub = a[a.trade_date >= start_dt].trade_date
            sub = sub[sub <= end_dt]
            sub.sort_values(ascending=False, inplace=True)
            res = sub.apply(lambda x: x.strftime('%Y-%m-%d')).values.tolist()
            print("Loaded %s days from %s to %s" % (len(res), res[-1], res[0]))
            #print(res)

        return res


    def error_handler(self, msg):
        if msg.typeName == "error": # and msg.id != -1:
            print("Server Error:", msg)