# -*- coding: utf-8 -*-
from requests.exceptions import RequestException

from events.data_sources.filters import (
    CharListFilter,
    ListFilterSet,
    ListOrCommaSeparatedStringListFilter,
)
from events.common_app.webmaster.api_client import WebMasterAPIClient
from events.data_sources.sources.base import BaseDataSourceCategory, BaseDataSource, SimpleDataSourceSerializer


class WebMasterDataSourceCategory(BaseDataSourceCategory):
    name = 'web_master'
    title = 'Вебмастер'


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

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


class WebSiteDataSourceFilter(ListFilterSet):
    id = ListOrCommaSeparatedStringListFilter(field_name=WebSiteDataSourceSerializer.id_attr)
    text = CharListFilter(field_name=WebSiteDataSourceSerializer.text_attr)


class WebSiteDataSource(BaseDataSource):
    name = 'web_master_site'
    title = 'Сайты в вебмастере'
    desc = 'Список сайтов пользователя в вебмастере'
    category = WebMasterDataSourceCategory()
    allow_external_usage = True
    is_need_auth = True
    serializer_class = WebSiteDataSourceSerializer
    filter_class = WebSiteDataSourceFilter
    hint = False
    allow_empty_filter = True
    max_filtered_result = None

    def get_queryset(self):
        sites = []
        if self.user and self.user.uid:
            try:
                sites = WebMasterAPIClient().list_user_hosts(self.user.uid)
            except RequestException:
                pass
        return sites
