from django.shortcuts import render, reverse, redirect, get_object_or_404
from django.urls import reverse, reverse_lazy
from django.views.generic.base import TemplateView
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from django.views.generic.edit import (
    FormView, CreateView, UpdateView, DeleteView, FormMixin
)
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.messages.views import SuccessMessageMixin
from django.contrib.auth.forms import PasswordChangeForm

from core.models import Comment, Post

from .models import User
from .forms import AccountUpdateForm


class AccountListView(LoginRequiredMixin, ListView):
    model = User
    template_name = 'accounts/account_list.html'


class AccountDetailView(LoginRequiredMixin, DetailView):
    model = User
    template_name = 'accounts/account_detail.html'

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context['posts'] = Post.objects.filter(author=self.object).order_by('-created_at')
        context['comments'] = Comment.objects.filter(author=self.object).order_by('-created_at')

        return context


class AccountUpdateView(LoginRequiredMixin, UserPassesTestMixin, SuccessMessageMixin, UpdateView):
    model = User
    form_class = AccountUpdateForm
    template_name = 'accounts/account_form.html'
    success_message = 'Account updated.'
    success_url = reverse_lazy('core:topic-list')

    def test_func(self):
        return self.request.user.pk == self.get_object().pk


class AccountDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
    model = User
    success_url = reverse_lazy('core:topic-list')

    def test_func(self):
        return self.request.user.pk == self.get_object().pk
