# encoding: utf-8
import datetime

from old_helper import BaseRepository
from typing import (
    Any,
    Optional
)

from ..model import Order


class OrderRepository(BaseRepository):

    def __init__(self, mb_context, pos_list):
        super(OrderRepository, self).__init__(mb_context)
        self.pos_list = pos_list

    def get_sales_by_date(
        self,
        user_id,                        # type: str
        start_date,                     # type: datetime.datetime
        end_date,                       # type: datetime.datetime
        by_created_order_time=False     # type: Optional[bool]
    ):
        # type: (...) -> Any

        def inner_func(conn):
            start_date_formatted = datetime.datetime.strftime(start_date, "%Y-%m-%dT%H:%M:%S")
            end_date_formatted = datetime.datetime.strftime(end_date, "%Y-%m-%dT%H:%M:%S")
            query_operator = "AND SessionId like '%user={0},%'".format(user_id) if len(user_id) > 0 else ""

            base_query = self._OrdersCreatedTimeQuery if by_created_order_time else self._OrdersQuery
            query = base_query.format(query_operator, start_date_formatted, end_date_formatted)

            orders = []
            for x in conn.select(query):
                orders.append(Order(x.get_entry("Timestamp"), x.get_entry("SaleType"), float(x.get_entry("Amount"))))
            return orders

        return self.execute_parallel_in_all_databases_returning_flat_list(inner_func, self.pos_list)

    _OrdersQuery = """\
    SELECT ocp.Value as Timestamp, st.TypeDescr as SaleType, o.TotalGross as Amount FROM Orders o
    INNER JOIN OrderCustomProperties ocp ON o.OrderId = ocp.OrderID
    INNER JOIN SaleType st ON o.SaleType = st.TypeId
    WHERE  o.stateid = 5 
        {0}
        AND KEY = 'FISCALIZATION_DATE'
        AND ocp.value >= '{1}'
        AND ocp.value < '{2}'
    ORDER BY Timestamp
    """

    _OrdersCreatedTimeQuery = """\
    SELECT st.TypeDescr as SaleType, o.TotalGross as Amount, o.CreatedAt as Timestamp FROM Orders o
    INNER JOIN SaleType st ON o.SaleType = st.TypeId
    WHERE  o.stateid in (2, 5, 8)
        {0}
        AND (o.OrderSubType <> 'SPLIT_SERVICE' OR o.OrderSubType IS NULL)
        AND o.CreatedAt >= '{1}'
        AND o.CreatedAt < '{2}'
    ORDER BY o.CreatedAt
    """
