# -*- coding: utf-8 -*-
import os

from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.views.generic import ListView, DetailView, FormView, DayArchiveView
from django.shortcuts import render, redirect
from django.utils.decorators import method_decorator

import tweepy
from pure_pagination.mixins import PaginationMixin

from authors.api import get_or_create_author

from .forms import TweetRegistrationForm, TweetImportForm
from .models import Tweet


class HomeView(PaginationMixin, ListView):
    template_name = 'home.html'
    paginate_by = 32
    queryset = Tweet.objects.filter(author__suspendedauthor__isnull=True)


class TweetListView(PaginationMixin, ListView):
    model = Tweet
    template_name = 'tweets/list.html'
    paginate_by = 32

    def get_queryset(self):
        queryset = super().get_queryset()
        return queryset.filter(author__screen_name=self.kwargs['slug'])


class TweetDetailView(DetailView):
    template_name = 'tweets/detail.html'
    model = Tweet


class TweetRegistrationView(FormView):
    template_name = 'tweets/registration.html'
    model = Tweet
    form_class = TweetRegistrationForm
    success_url = '/register'

    def _register_tweet(self, user, status, author):
        err_msg = None
        if self.model.objects.filter(id=status.id).exists():
            err_msg = "登録済みの tweet ID です。"
        elif status.author.id != user.twitter_id:
            err_msg = "他人のツイートは登録できません。"
        else:
            if 'media' in status.entities:
                self.model.objects.create(
                    id=status.id,
                    author=author,
                    text=status.text,
                    media_url=status.entities['media'][0]['media_url'],
                    created_at=status.created_at,
                )
            else:
                err_msg = "mediaが存在しないツイートです。"
        return err_msg

    @method_decorator(login_required(login_url='/login/twitter/'))
    def dispatch(self, *args, **kwargs):
        return super().dispatch(*args, **kwargs)

    def form_valid(self, form):
        try:
            status = self.request.twitter_api.get_status(id=form.cleaned_data['id'])
        except tweepy.TweepError:
            messages.error(self.request, "存在しない tweet ID です。")
            return redirect('register')

        author = get_or_create_author(status.author.id, status.author.name, status.author.screen_name)

        error_message = self._register_tweet(self.request.user, status, author)
        if error_message:
            messages.error(self.request, error_message)
        else:
            messages.success(self.request, "ツイートを登録しました")

        return super().form_valid(form)


class TweetImportView(FormView):
    template_name = 'tweets/import.html'
    model = Tweet
    form_class = TweetImportForm
    success_url = '/import'

    def _register_tweet(self, user, status, author):
        err_msg = None
        if self.model.objects.filter(id=status.id).exists():
            err_msg = "登録済みの tweet ID です。"
        elif status.author.id != user.twitter_id:
            err_msg = "他人のツイートは登録できません。"
        else:
            if 'media' in status.entities:
                self.model.objects.create(
                    id=status.id,
                    author=author,
                    text=status.text,
                    media_url=status.entities['media'][0]['media_url'],
                    created_at=status.created_at,
                )
            else:
                err_msg = "mediaが存在しないツイートです。"
        return err_msg

    @method_decorator(login_required(login_url='/login/twitter/'))
    def dispatch(self, *args, **kwargs):
        return super().dispatch(*args, **kwargs)

    def form_valid(self, form):
        d = form.cleaned_data['file']
        from tweets.utils import parse_csv
        for row in parse_csv(d, u"#艦これ版深夜の真剣お絵描き60分一本勝負"):
            if self.model.objects.filter(id=row['tweet_id']).exists():
                print("%s is already exists." % row['tweet_id'])
                continue
            else:
                try:
                    status = self.request.twitter_api.get_status(id=row['tweet_id'])
                except tweepy.TweepError:
                    continue

                author = get_or_create_author(status.author.id, status.author.name, status.author.screen_name)

                self.model.objects.create(
                    id=status.id,
                    author=author,
                    text=status.text,
                    media_url=status.entities['media'][0]['media_url'],
                    created_at=status.created_at,
                )

        return super().form_valid(form)


class TweetDayArchiveView(PaginationMixin, DayArchiveView):
    queryset = Tweet.objects.filter(author__suspendedauthor__isnull=True)
    date_field = "created_at"
    allow_future = True
    year_format = '%Y'
    month_format = '%m'
    day_format = '%d'
    template_name = 'tweets/archive_day.html'
    paginate_by = 32

    def tweets_count(self):
        return self.object_list.count()
