import logging

import persistence
from msgbus import MBEasyContext
from pos_model import (
    OrderKey,
    PosConnection,
)
from typing import (
    List,
    Optional,
)

logger = logging.getLogger("FiscalWrapperNfceDisabler")


class OrderRepository(object):
    def __init__(self, mbcontext, pos_list):
        # type: (MBEasyContext, list) -> None
        self.mbcontext = mbcontext
        self.pos_list = pos_list

    def get_all_orders_to_disable(self):
        # type: () -> List[OrderKey]

        orders_to_disable = []  # type: List[OrderKey]

        for pos_id in self.pos_list:  # type: int
            pos_connection = None  # type: Optional[PosConnection]

            try:
                pos_connection = persistence.Driver().open(self.mbcontext, dbname=str(pos_id))
                cursor = pos_connection.select("""
                    SELECT 
                        o.OrderId
                    FROM Orders o
                    INNER JOIN OrderCustomProperties ocp_include 
                        ON ocp_include.OrderId = o.OrderId 
                        AND ocp_include.key = 'FISCAL_ID'
                    LEFT JOIN OrderCustomProperties ocp_exclude 
                        ON ocp_exclude.OrderId = o.OrderId 
                        AND ocp_exclude.key in ('ORDER_DISABLED', 'CANCELED_AFTER_PAID')
                    WHERE ocp_exclude.OrderId IS NULL
                        AND o.StateId in ('4', '7')
                    ORDER BY o.OrderId DESC
                    LIMIT 100;
                """)

                if cursor and cursor.rows() > 0:
                    for row in cursor:
                        order_id = row.get_entry(0)
                        orders_to_disable.append(OrderKey(pos_id=str(pos_id), order_id=order_id))

            except Exception as _:
                logger.exception("Error getting orders to disable from pos [{}]".format(pos_id))
            finally:
                if pos_connection:
                    pos_connection.close()

        return orders_to_disable
