from __future__ import division

import math

from datetime import datetime, timedelta
from flask_restful import abort

from distribution import app
from distribution.adapters.utils import get_adapter
from distribution.models.sitemap_url import SitemapURL
from .base import ModelResource


class SitemapIndex(ModelResource):

    model = SitemapURL

    def get(self, domain):
        output_adapter = get_adapter("sitemap_index", is_public=True)

        result = self.model.manager.count(**{'domain': domain})

        if result['count'] == 0:
            abort(404, message='Not Found')

        context = {
            'total_pages': int(math.ceil(result['count'] / app.config['SITEMAP_MAX_ROWS_LIMIT'])),
            'domain': domain,
        }

        return output_adapter.render(context)


class SitemapPage(ModelResource):

    model = SitemapURL

    def get(self, domain, page):
        output_adapter = get_adapter("sitemap_page", is_public=True)

        sitemaps = self.model.manager.search(**{'domain': domain, 'page': page})

        if len(sitemaps) == 0:
            abort(404, message='Not Found')

        return output_adapter.render(sitemaps)


class SitemapNews(ModelResource):
    model = SitemapURL
    NEWS_DAYS = app.config['SITEMAP_MAX_DAYS_TO_SEARCH']

    def get(self, domain):
        domain = domain.lower()
        output_adapter = get_adapter("sitemap_news", is_public=True)
        difference = datetime.utcnow() - timedelta(days=self.NEWS_DAYS)
        from_datetime = difference.strftime("%Y-%m-%dT%H:%M:%SZ")
        search = {
            'domain': domain,
            'publication_datetime__from': from_datetime,
            'size': app.config['SITEMAP_MAX_ARTICLE_LIMIT']
        }
        if self.include_subdomain_condition(domain):
            search['subdomains'] = app.config['SITEMAP_ALLOWED_SUBDOMAINS']
        sitemaps = self.model.manager.search(**search)
        return output_adapter.render(sitemaps)

    @staticmethod
    def include_subdomain_condition(domain):
        for natgeo_domain in app.config['NATGEO_ALLOWED_DOMAINS']:
            if natgeo_domain in domain:
                return True
        return False
