# -*- coding: utf-8 -*-

from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.http import Http404
from django.shortcuts import (
    get_object_or_404,
    redirect,
    render,
)

from libra.books.forms import AddPublisherForm, DeletePublisherForm
from libra.books.models import Book, Publisher
from libra.shortcuts import response_json


@login_required(redirect_field_name=settings.REDIRECT_FIELD_NAME)
def list_publishers(request):
    publishers = Publisher.objects.all()
    return render(
        request,
        'list-publishers.html',
        {
            'publishers': publishers
        }
    )


def list_publishers_json(request):
    """
        Возвращает response со списком издательств, кодированный в json
    """
    q = request.REQUEST.get('q', '')
    if q:
        publishers = list(
            Publisher.objects.filter(name__istartswith=q).values('id', 'name')
        )
        return response_json(publishers)
    else:
        raise Http404


# WTF!?
@login_required(redirect_field_name=settings.REDIRECT_FIELD_NAME)
def view_publisher(request, pub_id):
    raise Http404


@login_required(redirect_field_name=settings.REDIRECT_FIELD_NAME)
def edit_publisher(request, pub_id):
    pub = get_object_or_404(Publisher, id=pub_id)
    if request.method == 'POST':
        f = AddPublisherForm(request.POST, instance=pub)
        if f.is_valid():
            f.save()
            return redirect('list_publishers')
    else:
        f = AddPublisherForm(instance=pub)
    return render(
        request,
        'form-publisher.html',
        {
            'form': f,
            'action': 'edit',
            'publisher': pub
        }
    )


@login_required(redirect_field_name=settings.REDIRECT_FIELD_NAME)
def add_publisher(request):
    '''
        Показывает /обрабатывает форму добавления издательства
    '''
    if request.method == 'POST':
        f = AddPublisherForm(request.POST)
        if f.is_valid():
            # WTF-2
            p = f.save()
            return redirect('list_publishers')
    else:
        f = AddPublisherForm()
    return render(
        request,
        'form-publisher.html',
        {
            'form': f,
            'action': 'add'
        }
    )


@login_required(redirect_field_name=settings.REDIRECT_FIELD_NAME)
def delete_publisher(request, pub_id):
    '''
        Удаление издательства с валидацией
        и заменой у книг на другое издательство
    '''
    # Проверим, есть ли связанные книги
    pub = get_object_or_404(Publisher, id=pub_id)
    books = Book.objects.filter(publisher=pub)

    if request.method == 'POST':
        # В форме выбора варианта удаления нажали сабмит
        f = DeletePublisherForm(request.POST)
        if f.is_valid():
            if f.cleaned_data['action_choices'] == 'replace':
                repl_publisher = f.cleaned_data['replace_publisher']
            elif f.cleaned_data['action_choices'] == 'keep_empty':
                repl_publisher = None

            if books:
                for b in books:
                    b.publisher = repl_publisher
                    b.save()
            pub.delete()

            return redirect('list_publishers')
        else:
            pass

    if books:  # Если есть, предложим вариант замены
        mode = 'OFFER_REPLACE'
        publishers = Publisher.objects.exclude(id=pub_id)
    else:
        mode = 'ACCEPT_ONLY'
        publishers = []

    if request.method == 'POST':
        f = DeletePublisherForm(
            request.POST, initial={'replace_publisher': publishers}
        )
    else:
        f = DeletePublisherForm(initial={'replace_publisher': publishers})

    return render(
        request,
        'form-delete-publisher.html',
        {
            'form': f,
            'pub': pub,
            'mode': mode,
            'books': books,
            'publishers': publishers
        }
    )
