from old_helper import BaseRepository
from datetime import datetime
from persistence import Connection
from ..model import Transfer
from typing import Optional, List


class AccountRepository(BaseRepository):
    TypeRealDate = "RealDate"
    TypeBusinessPeriod = "BusinessPeriod"
    TypeSessionId = "SessionId"

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

    def get_transfers_by_real_date(self, initial_date, end_date, operator_id, report_pos, session_id=None):
        # type: (datetime, datetime, str, str, Optional[unicode]) -> List[Transfer]
        return self._get_transfer(self.TypeRealDate, initial_date, end_date, operator_id, session_id, report_pos)

    def get_transfers_by_business_period(self, initial_date, end_date, operator_id, report_pos):
        # type: (datetime, datetime, str, str) -> List[Transfer]
        return self._get_transfer(self.TypeBusinessPeriod, initial_date, end_date, operator_id, None, report_pos)

    def get_transfers_by_session_id(self, session_id):
        # type: (unicode) -> List[Transfer]
        return self._get_transfer(self.TypeSessionId, None, None, None, session_id, None)

    def _get_transfer(self, report_type, initial_date, end_date, operator_id, session_id, report_pos):
        # type: (unicode, Optional[datetime], Optional[datetime], Optional[unicode], Optional[unicode], Optional[unicode]) -> List[Transfer] # noqa
        def inner_func(conn):
            # type: (Connection) -> List[Transfer]
            current_session_id = session_id if session_id is not None else ''
            if report_type == self.TypeRealDate or report_type == self.TypeBusinessPeriod:
                query = self._TransfersByRealDate
                if report_type == self.TypeBusinessPeriod:
                    query = self._TransfersByBusinessPeriod

                formatted_initial_date = initial_date.strftime("%Y-%m-%d")
                formatted_end_date = end_date.strftime("%Y-%m-%d")
                query = query.format(formatted_initial_date, formatted_end_date, current_session_id)

                if operator_id is not None:
                    query += " and SessionId like '%user={0},%'".format(operator_id)

                if report_pos is not None:
                    query += " and PosId = {0}".format(report_pos)
            else:
                query = self._TransfersBySessionId
                query = query.format(session_id)


            return [Transfer(int(x.get_entry(0)), float(x.get_entry(1))) for x in conn.select(query)]

        return self.execute_with_connection(inner_func)

    _TransfersByRealDate = """
                                SELECT Type, Amount 
                                FROM Transfer
                                WHERE strftime('%Y-%m-%d', Timestamp, 'localtime') >= '{0}' AND
                                strftime('%Y-%m-%d', Timestamp, 'localtime') <= '{1}' AND
                                SessionId LIKE '%{2}%'
                            """

    _TransfersByBusinessPeriod = """
                                    SELECT Type, Amount 
                                    FROM Transfer 
                                    WHERE Period >= strftime('%Y%m%d', '{0}') AND 
                                          Period <= strftime('%Y%m%d', '{1}') AND SessionId LIKE '%{2}%'
                                """

    _TransfersBySessionId = """
                                SELECT Type, Amount 
                                FROM Transfer
                                WHERE SessionId = '{0}'
                            """
