# encoding: utf-8

from old_helper import BaseRepository


class DeliveryProductRepository(BaseRepository):

    def __init__(self, mb_context):
        super(DeliveryProductRepository, self).__init__(mb_context)

    def get_products(self):
        def inner_func(conn):
            products = {}
            query = self._ProductsQuery

            for x in conn.select(query):
                product_code = x.get_entry("ProductCode")
                product_name = x.get_entry("ProductName")
                product_type = x.get_entry("ProductType").replace("TYPE_", "")
                products[product_code] = (product_name, product_type)

            return products

        return self.execute_with_connection(inner_func)

    def get_cfh_products(self):
        def inner_func(conn):
            cfh_products = []
            query = self._CFHQuery

            for x in conn.select(query):
                cfh_products.append(x.get_entry("ProductCode"))

            return cfh_products

        return self.execute_with_connection(inner_func)

    _ProductsQuery = """
                    SELECT DISTINCT p.ProductCode, p.ProductName, pt.TypeDescr as ProductType
                    FROM Product p
                    INNER JOIN ProductKernelParams pkp ON pkp.ProductCode = p.ProductCode
                    JOIN ProductType pt ON pt.TypeId = pkp.ProductType
                  """

    _CFHQuery = """
                    SELECT ProductCode FROM ProductTags
                    WHERE LOWER(Tag) = 'cfh=true'
                    UNION
                    SELECT ProductCode FROM ProductCustomParams
                    WHERE LOWER(CustomParamId) = 'cfh' AND LOWER(CustomParamValue) = 'true'
                """
