#!/srv/venv/bin/python

import sys
import os

import requests
import datetime
import arrow

PY3K = sys.version_info >= (3,0)

from django.core.management.base import BaseCommand
from rowers.models import BlogPost

class Command(BaseCommand):
    def handle(self, *args, **options):
        blogs_json = []
        try:
            response = requests.get(
                'https://analytics.rowsandall.com/wp-json/wp/v2/posts?per_page=3')
            if response.status_code == 200:
                blogs_json = response.json()
            else:
                blogs_json = []
        except ConnectionError:
            pass

        if blogs_json:
            result = BlogPost.objects.all().delete()

            for postdata in blogs_json[0:3]:
                title = postdata['title']['rendered']
                link = postdata['link']
                datetime = postdata['date']
                datetime = arrow.get(datetime).datetime
                date = datetime.date()


                blogpost = BlogPost(
                    link=link,
                    date=date,
                    title=title
                )

                blogpost.save()

        self.stdout.write(self.style.SUCCESS(
            'Successfully processed blog posts'))

