from viggocore.common.subsystem.driver import Driver
from viggocore.common.subsystem import operation
from viggocore.common import exception
from viggocore.common.subsystem.manager_functions import make_exportar_xlsx


class ExportarXlsx(operation.List):
    def pre(self, **kwargs):
        self.title = 'Exportação em XLSX'
        self.file_title = 'exportacao_xlsx'
        return True

    def do(self, session, **kwargs):
        filters = kwargs.get('filters', {})
        columns = kwargs.get('columns', [])
        entities, _ = self.manager.list(session=session, **filters)
        if len(entities) > 0:
            download_folder, file_name = \
                self.manager.make_exportar_xlsx(
                    entities=entities,
                    columns=columns,
                    title=self.title,
                    file_title=self.file_title
                )
        else:
            raise exception.BadRequest(
                'Não existe nada para essa filtragem.')

        return download_folder, file_name


class Manager(object):

    def __init__(self, driver: Driver) -> None:
        self.driver = driver

        self.create = operation.Create(self)
        self.get = operation.Get(self)
        self.list = operation.List(self)
        self.update = operation.Update(self)
        self.delete = operation.Delete(self)
        # NOTE(samueldmq): what do we use this for ?
        self.count = operation.Count(self)
        self.list_multiple_selection = operation.ListMultipleSelection(self)
        self.activate_or_deactivate_multiple_entities = operation.\
            ActivateOrDeactivateMultipleEntities(self)
        self.exportar_xlsx = ExportarXlsx(self)
        self.make_exportar_xlsx = make_exportar_xlsx.MakeExportarXsls(self)

    def init_query(self, session, order_by, resource):
        raise exception.BadRequest(
            f'Method _init_query() not implemented for {resource.__name__}.')

    def valid_dinamic_order_by(self, order_by):
        result = False
        count_points = order_by.count('.')
        if ('.' in order_by and count_points == 1) or count_points == 0:
            result = True
        elif count_points > 1:
            raise exception.BadRequest(
                'order_by item cannot have more than one point.')
        return result

    def get_multiple_selection_ids(self, entities):
        try:
            return [entity.id for entity in entities]
        except Exception:
            raise exception.BadRequest(
                'id is not an attribute of this entity')
