class BittrexPipeline(object):
    def __init__(self, on_market_summary, poll_time=15, minor_currency="BTC"):
        '''
        on_market_summary should have 1 parameter: the json object containing the market summary
                                                   as specified by Bittrex's API.
        
        Pre: poll_time is a positive integer
        Post: on_market_summary is called every [poll_time] seconds for every market that has
              [minor_currency] as the minor currency.
        '''
        
        self.on_market_summary = on_market_summary
        self.bittrex_api = Bittrex(BittrexSecret.api_key, BittrexSecret.api_secret)
        self.poll_time = poll_time
        self._time_started = 0
        self.minor_currency = minor_currency
        
        self.stop = False
        self.thread = None

    def _start(self, get_market):
        def _go():
            last_time = 0
            while True:
                if self.stop:
                    print "Stopping Bittrex pipeline."
                    break
                elif time.time() - last_time >= self.poll_time:
                    last_time = time.time()
                    get_market()

        self.thread = Thread(target=_go)
        self.stop = False
        self.thread.start()

    def start_singlemarket(self, market):
        def _get_market():
            market_summary = self.bittrex_api.get_marketsummary(self.market)["result"][0]
            trading = market_summary["MarketName"].replace(self.minor_currency+"-", '')
            self.on_market_summary(market_summary, trading)
            
        self.market = market
        self._start(_get_market)
        print("Started Bittrex pipeline for market: " +market)
        

    def start_multimarket(self):
        def _get_market():
            market_summaries = self.bittrex_api.get_market_summaries()
            for market_summary in market_summaries["result"]:
                if market_summary["MarketName"].startswith(self.minor_currency):
                    trading = market_summary["MarketName"].replace(self.minor_currency+"-", '')
                    self.on_market_summary(market_summary, trading)

        self._start(_get_market)
        print("Started Bittrex pipeline for all markets with the minor currency "+self.minor_currency+".")

    def stop(self):
        if not self.stop:
            self.stop = True
class TestBittrexV20PublicAPI(unittest.TestCase):
    """
    Integration tests for the Bittrex public API.
    These will fail in the absence of an internet connection or if bittrex API goes down
    """

    def setUp(self):
        self.bittrex = Bittrex(None, None, api_version=API_V2_0)

    def test_handles_none_key_or_secret(self):
        self.bittrex = Bittrex(None, None, api_version=API_V2_0)
        # could call any public method here
        actual = self.bittrex.get_markets()
        self.assertTrue(actual['success'], "failed with None key and None secret")

        self.bittrex = Bittrex("123", None, api_version=API_V2_0)
        actual = self.bittrex.get_markets()
        self.assertTrue(actual['success'], "failed with None secret")

        self.bittrex = Bittrex(None, "123", api_version=API_V2_0)
        actual = self.bittrex.get_markets()
        self.assertTrue(actual['success'], "failed with None key")

    def test_get_markets(self):
        actual = self.bittrex.get_markets()
        test_basic_response(self, actual, "get_markets")
        self.assertTrue(isinstance(actual['result'], list), "result is not a list")
        self.assertTrue(len(actual['result']) > 0, "result list is 0-length")

    def test_get_currencies(self):
        actual = self.bittrex.get_currencies()
        test_basic_response(self, actual, "get_currencies")

    def test_get_ticker(self):
        self.assertRaisesRegexp(Exception, 'method call not available', self.bittrex.get_ticker,
                                market='BTC-LTC')

    def test_get_market_summaries(self):
        actual = self.bittrex.get_market_summaries()
        test_basic_response(self, actual, "get_market_summaries")

    def test_get_market_summary(self):
        actual = self.bittrex.get_marketsummary(market='BTC-LTC')
        test_basic_response(self, actual, "get_marketsummary")

    def test_get_orderbook(self):
        actual = self.bittrex.get_orderbook('BTC-LTC')
        test_basic_response(self, actual, "get_orderbook")

    def test_get_market_history(self):
        actual = self.bittrex.get_market_history('BTC-LTC')
        test_basic_response(self, actual, "get_market_history")

    def test_list_markets_by_currency(self):
        actual = self.bittrex.list_markets_by_currency('LTC')
        self.assertListEqual(['BTC-LTC', 'ETH-LTC', 'USDT-LTC'], actual)

    def test_get_wallet_health(self):
        actual = self.bittrex.get_wallet_health()
        test_basic_response(self, actual, "get_wallet_health")
        self.assertIsInstance(actual['result'], list)

    @unittest.skip("Endpoint 404s.  Is this still a valid 2.0 API?")
    def test_get_balance_distribution(self):
        actual = self.bittrex.get_balance_distribution()
        test_basic_response(self, actual, "get_balance_distribution")
        self.assertIsInstance(actual['result'], list)

    def test_get_candles(self):
        actual = self.bittrex.get_candles('BTC-LTC', tick_interval=TICKINTERVAL_ONEMIN)
        test_basic_response(self, actual, "test_get_candles")
        self.assertIsInstance(actual['result'], list)