from django.shortcuts import render, redirect, get_object_or_404
from django.views import View
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib import messages
from .models import Rider
from .forms import RiderForm


class RiderManagementView(LoginRequiredMixin, View):
	def get(self, request):
		riders = Rider.objects.all()
		return render(request, 'pages/rider-management/rider_management.html', {'riders': riders})


class RiderCreateView(LoginRequiredMixin, View):
	def get(self, request):
		return render(request, 'pages/rider-management/rider_create.html')

	def post(self, request):
		form = RiderForm(request.POST, request.FILES)
		if form.is_valid():
			form.save()
			messages.success(request, 'Rider created successfully!')
			return redirect('rider-management')
		else:
			# render form with errors
			return render(request, 'pages/rider-management/rider_create.html', {'form': form})


class RiderDetailViewWeb(LoginRequiredMixin, View):
	def get(self, request, pk):
		rider = get_object_or_404(Rider, pk=pk)
		return render(request, 'pages/rider-management/rider_detail.html', {'rider': rider})


class RiderEditView(LoginRequiredMixin, View):
	def get(self, request, pk):
		rider = get_object_or_404(Rider, pk=pk)
		return render(request, 'pages/rider-management/rider_edit.html', {'rider': rider})

	def post(self, request, pk):
		rider = get_object_or_404(Rider, pk=pk)
		form = RiderForm(request.POST, request.FILES, instance=rider)
		if form.is_valid():
			form.save()
			messages.success(request, 'Rider updated successfully!')
			return redirect('rider-management')
		else:
			return render(request, 'pages/rider-management/rider_edit.html', {'rider': rider, 'form': form})


class RiderDeleteView(LoginRequiredMixin, View):
	def post(self, request, pk):
		rider = get_object_or_404(Rider, pk=pk)
		rider.trash = True
		rider.save()
		messages.success(request, 'Rider deleted (trashed) successfully!')
		return redirect('rider-management')

