# -*- coding: utf-8 -*-
from django.utils.translation import ugettext as _

from events.data_sources.exceptions import WrongExternalTableSchemaError
from events.data_sources.sources.base import (
    BaseDataSource,
    BaseDataSourceCategory,
    SimpleDataSourceSerializer,
)


class ExternalTableDataSourceCategory(BaseDataSourceCategory):
    name = 'external_table_source'
    title = 'Табличный источник данных'


class ExternalTableDataSourceSerializer(SimpleDataSourceSerializer):
    id_attr = 'id'
    text_attr = 'name'

    class Meta:
        fields = ('id', 'name')


class BaseExternalTableDataSource(BaseDataSource):

    category = ExternalTableDataSourceCategory()
    serializer_class = ExternalTableDataSourceSerializer
    allow_external_usage = True
    is_with_pagination = True
    is_proxy_data_source = True
    hint = False

    def get_queryset(self):
        pass

    @classmethod
    def get_view_class(cls):
        from events.data_sources.api.views import DataSourceBaseViewSet
        return DataSourceBaseViewSet

    @staticmethod
    def sync_table_with_db(param_data_source_param):
        raise NotImplementedError


class BaseExternalTableDataSourceFilter(object):
    def __init__(self, filter_data, queryset):
        self.queryset = queryset
        self.filter_data = filter_data

    def _get_data(self, url):
        raise NotImplementedError

    @property
    def qs(self):
        data = []
        if self.filter_data:
            self.suggest = self.filter_data.get('suggest', '').lower()
            self.ids_passed = self.filter_data.get('id')
            url = self.filter_data.get('free_url')
            if url:
                try:
                    data = self._get_data(url)
                except KeyError:
                    raise WrongExternalTableSchemaError(_('Указана таблица с некорректной схемой данных'))
        return data or []
