# encoding: utf-8
from old_helper import BaseRepository
from ..model import Account
import json

from domain import TransferType


class AccountRepository(BaseRepository):

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

    def get_all_transfers(self, session):
        def inner_func(conn):
            query = self._AccountQuery.format(session)
            transfers = []
            for x in conn.select(query):
                transfers.append(Account(int(x.get_entry("Type")),
                                         float(x.get_entry("Amount")),
                                         int(x.get_entry("TenderId")),
                                         x.get_entry("Timestamp"),
                                         x.get_entry("GLAccount")
                                         )
                                 )
            return transfers

        return self.execute_with_connection(inner_func)

    def get_authorizer(self, session):
        def inner_func(conn):
            try:
                query = self._AccountAuthorizerQuery.format(session, TransferType.FINAL_AMOUNT)
                for x in conn.select(query):
                    return json.loads(x.get_entry("GLAccount"))["manager"]

                return None
            except Exception as _:
                return None

        return self.execute_with_connection(inner_func)

    _AccountQuery = """\
        SELECT 
            Type, 
            COALESCE(Amount, 0) as Amount, 
            TenderId, 
            Timestamp, 
            GLAccount
        FROM Transfer
        WHERE SessionId = '{}'
        """

    _AccountAuthorizerQuery = """\
    SELECT GLAccount
    FROM Transfer
    WHERE SessionId = '{}' AND Type = '{}'
    """
