from distribution import settings


class BaseAMPRule(object):
    """Rules to check if an article should be or not
    renderizable by the AMPAdapter.
    """

    CONTENT_TYPE = None

    allowed_sources = []
    allowed_genres = []
    excluded_domains = [settings.GLOBALSITES]

    @classmethod
    def check_content_type(cls, content_type):
        return cls.CONTENT_TYPE == content_type

    @property
    def sources(self):
        return [settings.SOURCES_MAP[s] for s in self.allowed_sources]

    @property
    def genres(self):
        return [settings.GENRES_MAP[g] for g in self.allowed_genres]

    def _check_allowed_domains(self, domain):
        if domain:
            return not any(
                excluded_domain in domain
                for excluded_domain in self.excluded_domains
            )
        return False

    def _check_allowed_sources(self, sources):
        return any(s in sources for s in self.sources)

    def _check_allowed_genres(self, genres):
        return any(g in genres for g in self.genres)

    def validate(self, domain, sources, genres):
        raise NotImplementedError()


class ArticleStoryAMPRule(BaseAMPRule):
    CONTENT_TYPE = 'article:story'

    allowed_sources = [
        settings.ADVENTURE,
        settings.NEWS,
        settings.PHOTOGRAPHY,
        settings.TRAVEL,
        settings.CULTURE_EXPLORATION,
    ]
    allowed_genres = [settings.NEWS]

    def validate(self, domain, sources, genres):
        condition_domain = self._check_allowed_domains(domain)
        condition_sources = self._check_allowed_sources(sources)
        condition_genres = self._check_allowed_genres(genres)
        return condition_domain and (condition_sources or condition_genres)


class ArticleReferenceAMPRule(BaseAMPRule):
    CONTENT_TYPE = 'article:reference'

    allowed_sources = [settings.ANIMALS]
    allowed_genres = [settings.ANIMALS]

    def validate(self, domain, sources, genres):
        condition_domain = self._check_allowed_domains(domain)
        condition_sources = self._check_allowed_sources(sources)
        condition_genres = self._check_allowed_genres(genres)
        return condition_domain and condition_sources and condition_genres


class ArticleImageGalleryAMPRule(ArticleStoryAMPRule):
    """For convert Article Image Gallery pages to AMP pages
    """
    CONTENT_TYPE = 'article:image_gallery'


class ArticleInteractiveAMPRule(ArticleStoryAMPRule):
    """Allows article:interactive content
    """
    CONTENT_TYPE = 'article:interactive'


class AMPRuleManager(object):
    """Obtains an AMP Rule by content type."""

    rules = [
        ArticleStoryAMPRule,
        ArticleReferenceAMPRule,
        ArticleImageGalleryAMPRule,
        ArticleInteractiveAMPRule
    ]

    def get_amp_rule(self, content_type):
        for rule in self.rules:
            if rule.check_content_type(content_type):
                return rule()
