"""The sample requests QFormula definition by QFormula name and waits for responses for 20 sec"""

import logging
import threading

import win32com.client

import CELEnvironment

#region Settings

# Replace it with any other existing QFormula
QFORMULA_NAME = "Q.Crack"

# Events waiting time
TIMEOUT = 20

# 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 QFormulaDefinitionByName(CELEnvironment.CELSinkBase):
    def __init__(self):
        self.celEnvironment = None
        self.eventDone = threading.Event()

    def Init(self, celEnvironment):
        self.celEnvironment = celEnvironment

    def Start(self):
        LOG.info("Request QFormula definition with name '%s'", QFORMULA_NAME)
        self.celEnvironment.cqgCEL.RequestQFormulaDefinition(QFORMULA_NAME)

        LOG.info("Waiting for results for 20 seconds...")
        self.eventDone.wait(TIMEOUT)

        LOG.info("Done!")

    def OnQFormulaDefinitionResolvedEx(self, requestStr, cqgQFormulaDefinition, cqgError):
        if cqgError is not None:
            error = win32com.client.Dispatch(cqgError)
            LOG.error("OnQFormulaDefinitionResolvedEx[%s]: Error. Code: %d Description: %s",
                      requestStr, error.Code, error.Description)
        else:
            definition = win32com.client.Dispatch(cqgQFormulaDefinition)
            LOG.info("OnQFormulaDefinitionResolvedEx[%s]: QNumber: %d QName: '%s'\n"
                     "Underlying expression:\n%s\nExecution pattern:\n%s\n",
                     requestStr, definition.Number, definition.Name,
                     definition.Expression, definition.ExecutionPattern)
        self.eventDone.set()


if __name__ == "__main__":
    CELEnvironment.Start(QFormulaDefinitionByName)
