from django.shortcuts import render, redirect, get_object_or_404
from .models import Book, Transaction
from .forms import BookForm, IssueBookForm
from django.utils import timezone

def index(request):
    books = Book.objects.all()
    context = {
        'books': books,
        'project_name': 'Library',
    }
    return render(request, 'core/index.html', context)

def add_book(request):
    if request.method == 'POST':
        form = BookForm(request.POST)
        if form.is_valid():
            book = form.save(commit=False)
            book.available_copies = book.total_copies
            book.save()
            return redirect('index')
    else:
        form = BookForm()
    context = {
        'form': form,
        'project_name': 'Library',
    }
    return render(request, 'core/add_book.html', context)

def issue_book(request, book_id):
    book = get_object_or_404(Book, id=book_id)
    if request.method == 'POST':
        form = IssueBookForm(request.POST)
        if form.is_valid():
            if book.available_copies > 0:
                transaction = form.save(commit=False)
                transaction.book = book
                transaction.save()
                book.available_copies -= 1
                book.save()
                return redirect('index')
            else:
                # Handle case where no copies are available
                pass
    else:
        form = IssueBookForm()
    context = {
        'form': form,
        'book': book,
        'project_name': 'Library',
    }
    return render(request, 'core/issue_book.html', context)

def transactions(request):
    transactions = Transaction.objects.all().order_by('-issue_date')
    context = {
        'transactions': transactions,
        'project_name': 'Library',
    }
    return render(request, 'core/transactions.html', context)

def return_book(request, transaction_id):
    transaction = get_object_or_404(Transaction, id=transaction_id)
    if not transaction.is_returned:
        transaction.is_returned = True
        transaction.return_date = timezone.now()
        transaction.save()
        transaction.book.available_copies += 1
        transaction.book.save()
    return redirect('transactions')
