# -*- coding: utf-8 -*-
import json
from datetime import datetime


from msgbus import MBEasyContext
from old_helper import BaseRepository
from persistence import Connection

from ..model import SaleChallengeItem


class SaleChallengeRepository(BaseRepository):

    def __init__(self, mb_context):
        # type: (MBEasyContext) -> None
        super(SaleChallengeRepository, self).__init__(mb_context)

    def get_sale_challenge(self, sale_challenge_id):
        # type: (int) -> SaleChallengeItem

        def inner_func(conn):
            # type: (Connection) -> SaleChallengeItem

            query = self._SaleChallengeProductsQuery
            cursor = conn.select(query.format(sale_challenge_id))
            row = cursor.get_row(0)
            return SaleChallengeItem(row.get_entry("Name"),
                                     datetime.strptime(row.get_entry("StartDate"), "%Y-%m-%d"),
                                     datetime.strptime(row.get_entry("EndDate"), "%Y-%m-%d"),
                                     json.loads(row.get_entry("Products") or "[]"))
        return self.execute_with_connection(inner_func, service_name="DailyGoalsPersistence")

    _SaleChallengeProductsQuery = """\
        SELECT *
        FROM SalesChallenge
        WHERE Id = {0}
    """
