# 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 row in conn.select(query):
                amount = row.get_entry("Amount")
                transfers.append(Account(
                    account_type=int(row.get_entry("Type")),
                    amount=float(amount or 0),
                    tender_id=int(row.get_entry("TenderId")),
                    operation_date=row.get_entry("Timestamp"),
                    glaccount=row.get_entry("GLAccount"),
                    is_undeclared=amount is None,
                ))
            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):
                    account = json.loads(x.get_entry("GLAccount"))
                    return account.get("manager", None)

                return None
            except Exception as _:
                return None

        return self.execute_with_connection(inner_func)

    _AccountQuery = """\
        SELECT 
            Type, 
            Amount, 
            TenderId, 
            Timestamp, 
            GLAccount
        FROM Transfer
        WHERE SessionId = '{}'
        """

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