"""The sample demonstrates how to defind UDS and place a strategy order"""

import logging
import threading

import win32com.client
from win32com.client import constants

import CELEnvironment
from CELEnvironment import AssertMessage

#region Settings

# Replace it with real login before run
LOGIN = "your_gw_login"
PASSWORD = "your_gw_password"

# Replace it with enabled symbol
STRATEGY = "UDS(-C.US.CLE?1+C.US.CLE?2, CalC)"

# Events waiting time
TIMEOUT = 10

# Logging settings: specify log level and log format here.
# Set log level to DEBUG to see more internal messages.
# See more information about logging lib usage: https://docs.python.org/3/howto/logging-cookbook.html
CELEnvironment.LOG_LEVEL = logging.INFO
# CELEnvironment.LOG_FORMAT = ...

# CELEnvironment.SinkInternal uses own LOG_LEVEL (which is inherited from the global one) and own LOG_FORMAT.
# You can redefine them as follows:
# CELEnvironment.SinkInternal.LOG_LEVEL = logging.DEBUG
# CELEnvironment.SinkInternal.LOG_FORMAT = ...

LOG = CELEnvironment.GetLogger()

#endregion


class UDSPlacingSample(CELEnvironment.CELSinkBase):
    def __init__(self):
        self.account = None
        self.instrument = None
        self.uds = None
        self.eventGatewayIsUp = threading.Event()
        self.eventGatewayIsDown = threading.Event()
        self.eventAccountIsReady = threading.Event()
        self.eventUDSIsReady = threading.Event()
        self.eventOrderPlaced = threading.Event()

    def Init(self, celEnvironment):
        self.celEnvironment = celEnvironment

    def Start(self):
        LOG.info("Connecting to GW")
        self.celEnvironment.cqgCEL.GWLogon(LOGIN, PASSWORD)

        LOG.info("Waiting for GW connection...")
        AssertMessage(self.eventGatewayIsUp.wait(TIMEOUT), "GW connection timeout!")

        self.celEnvironment.cqgCEL.AccountSubscriptionLevel = constants.aslAccountUpdatesAndOrders
        LOG.info("Waiting for accounts coming...")
        AssertMessage(self.eventAccountIsReady.wait(TIMEOUT), "Accounts coming timeout!")

        accounts = win32com.client.Dispatch(self.celEnvironment.cqgCEL.Accounts)
        # Select an account that has enablement for UDS
        self.account = win32com.client.Dispatch(accounts.ItemByIndex(0))

        LOG.info("Define strategy...")
        self.uds = self.celEnvironment.cqgCEL.DefineStrategyEx(STRATEGY, self.account)

        LOG.info("UDS waiting...")
        AssertMessage(self.eventUDSIsReady.wait(TIMEOUT), "UDS resolution timeout!")

        dispatchedUDS = win32com.client.Dispatch(self.uds)
        dispatchedOrder = win32com.client.Dispatch(
            self.celEnvironment.cqgCEL.CreateStrategyOrder(constants.otLimit, dispatchedUDS, self.account, None, 1,
                                                           constants.osdUndefined, 3.15))
        dispatchedOrder.Place()

        LOG.info("Waiting for order placing...")
        AssertMessage(self.eventOrderPlaced.wait(TIMEOUT), "Order placing timeout!")

        LOG.info("Logoff from GW")
        self.eventGatewayIsDown.clear()
        self.celEnvironment.cqgCEL.GWLogoff()
        AssertMessage(self.eventGatewayIsDown.wait(TIMEOUT), "GW disconnection timeout!")

        LOG.info("Done!")

    def OnGWConnectionStatusChanged(self, newStatus):
        if newStatus == constants.csConnectionUp:
            LOG.info("GW connection is UP!")
            self.eventGatewayIsUp.set()
        if newStatus == constants.csConnectionDown:
            LOG.info("GW connection is DOWN!")
            self.eventGatewayIsDown.set()

    def OnAccountChanged(self, changeType, cqgAccount, cqgPosition):
        if changeType != constants.actAccountsReloaded:
            return

        LOG.info("Accounts are ready!")
        self.eventAccountIsReady.set()

    def OnStrategyDefinitionProgress(self, cqgDefinition, cqgError):
        if cqgError is not None:
            error = win32com.client.Dispatch(cqgError)
            LOG.error("OnStrategyDefinitionProgress error: Code: %d Description: %s", error.Code, error.Description)
            return

        definition = win32com.client.Dispatch(cqgDefinition)
        LOG.info("OnStrategyDefinitionProgress: requested symbol: %s GW symbol: %s status: %d",
                 definition.RequestString, definition.Symbol, definition.Status)
        if definition.Status == constants.srsSuccess:
            self.eventUDSIsReady.set()

    def OnOrderChanged(self, changeType, cqgOrder, oldProperties, cqgFill, cqgError):
        if cqgError is not None:
            error = win32com.client.Dispatch(cqgError)
            LOG.error("OnOrderChanged error: Code: %d Description: %s", error.Code, error.Description)
            return

        dispatchedOrder = win32com.client.Dispatch(cqgOrder)
        properties = win32com.client.Dispatch(dispatchedOrder.Properties)
        gwStatus = properties(constants.opGWStatus)
        quantity = properties(constants.opQuantity)
        instrument = properties(constants.opInstrumentName)
        limitPrice = properties(constants.opLimitPrice)

        LOG.info(
            "OnOrderChanged: change type: %d; GW status: %d; Quantity: %d; Instrument: %s; Price: %f;",
            changeType,
            gwStatus,
            quantity,
            instrument,
            limitPrice
        )

        if changeType != constants.ctChanged:
            return

        if gwStatus.Value == constants.osInOrderBook:
            LOG.info("UDS order is placed!")
            self.eventOrderPlaced.set()


if __name__ == "__main__":
    CELEnvironment.Start(UDSPlacingSample)
