#!/usr/bin/env python3
# -*- coding: utf-8 -*-


from decimal import Decimal as D

from utils.hmath import check_dec_is_n_places
from utils.time.tools import timestamp_to_printable as ts2p

import currencies

from events.base import BaseEvent




class Order(BaseEvent):

  '''
  Represent a single order.  This can come from a third party on the exchange or
  from ourselves.
  '''

  STATE_CREATED   = 1
  STATE_CHANGED   = 2
  STATE_DELETED   = 3


  def __init__( self, exchange_id, price, volume, state,
                ts_update, ts_create=None, ts_delete=None, 
                order_id=None):
    '''
    `exchange_id` - ID of the exchange this order is on
    `price`       - duh
    `volume`      - duh
    `state`       - State, must be from Order.STATE_*
    `ts_create`   - optional, epoch timestamp when order was created
    `ts_delete`   - optional, epoch timestamp when order was deleted
    `ts_update`   - when we heard about this order from the exchange
    `order_id`    - unique id for this order, generated by exchange
    '''
    super(Order,self).__init__(exchange_id, ts_update)
    if price is not None and not check_dec_is_n_places(price, 2):
      raise ValueError("Price is up to 2 decimal places, not '%s'" % price)
    self.price = price

    if not check_dec_is_n_places(volume, 8):
      raise ValueError("volume up to 8 decimal places, not '%s'" % volume)
    self.volume = volume

    self.ts_create    = ts_create
    self.ts_delete    = ts_delete

    self.order_id     = order_id

    if state not in (Order.STATE_CREATED, Order.STATE_CHANGED, Order.STATE_DELETED):
      raise ValueError("order_state must be one of Order.STATE_CREATED, Order.STATE_CHANGED, Order.STATE_DELETED")
    self.order_state  = state


  def __str__(self):
    if self.ts_delete is None:
      return "<%s %s%.8f @ c%.2f C:%s>" % (
        self.__class__.__name__,
        currencies.CurrencyBTC.SYMBOL, self.volume,
        self.price, ts2p(self.ts_create)
      )
    else:
      return "<%s %s%.8f @ %.2f C:%s D:%s>" % (
        self.__class__.__name__,
        currencies.CurrencyBTC.SYMBOL,
        self.volume,  self.price,
        ts2p(self.ts_create),
        ts2p(self.ts_delete)
      )


  def latency(self):
    '''
    What was the delay between the create/update timestamp (i.e. when the
    exchange generated this object) and its arrival here?
    '''
    ts = self.ts_delete if self.ts_delete is not None else self.ts_create
    return self.ts_update - ts





class OrderAsk(Order):
  "AKA sell"

class OrderBid(Order):
  "AKA buy"


