from django.shortcuts import render, redirect, get_object_or_404
from django.urls import reverse
from django.views.generic import TemplateView
from django.core.files.storage import FileSystemStorage
from django.contrib import messages
from django.conf import settings
from django.views.generic import CreateView,DetailView,ListView,UpdateView,DeleteView
import os, csv, io, datetime
from django.contrib.messages.views import SuccessMessageMixin
from django.db.models import Q

from .forms import BookForm, VideoForm, KellerModelForm
from .models import Book, Video, Keller


class KellerListView(ListView):
	template_name = 'chemie/keller_list.html' # <app>/modelname_list.html
	queryset = Keller.objects.all().order_by('name')
	
	def get_queryset(self):
		query = self.request.GET.get('q')
		if query == '' or query == None :
			list = Keller.objects.all().order_by('name')
		else :
			if query[0].isdigit():
				list = Keller.objects.filter(Q(kiste__exact=query))		# startswith| endswith | <blog>_id
			else:
				list = Keller.objects.filter(Q(name__icontains=query)) # not case-sensitive
		return list
		
class KellerDetailView(DetailView):
	template_name = 'chemie/keller_detail.html' # <app>/modelname_list.html
	#queryset = Keller.objects.all()	
	def get_object(self):
		id_ = self.kwargs.get("id")
		return get_object_or_404(Keller,id=id_)

class KellerCreateView(SuccessMessageMixin,CreateView):
	template_name = 'chemie/keller_create.html'
	form_class = KellerModelForm
	queryset = Keller.objects.all()
	success_message = "%(name)s was created"
	
class KellerUpdateView(UpdateView):
	template_name = 'chemie/keller_create.html'
	form_class = KellerModelForm
	queryset = Keller.objects.all()
	def get_object(self):
		id_ = self.kwargs.get("id")
		return get_object_or_404(Keller,id=id_)	

class KellerDeleteView(DeleteView):
	template_name = 'chemie/keller_delete.html' # <app>/modelname_list.html
	queryset = Keller.objects.all()

	def get_object(self):
		id_ = self.kwargs.get("id")
		return get_object_or_404(Keller,id=id_)
		
	def get_success_url(self):
		return reverse('keller-list')
		
		
def keller_upload(request):
	template = "chemie/csv_upload.html"
	prompt ={
		'order': ' Order im csv file "Name","Menge","Einheit","Kiste","Nr" '
	}
	if request.method == 'GET':
		return render(request, template, prompt)
		
	csv_file = request.FILES['upfile']
	
	if not csv_file.name.endswith('.csv'):
		messages.error(request,'This is not a csv-file')
	data_set = csv_file.read().decode('UTF-8')
	io_string = io.StringIO(data_set)
	next(io_string)
	for col in csv.reader(io_string, delimiter=','):
		print(col)
		_, created = Keller.objects.update_or_create(
			name=col[0],
			menge=col[1],
			einheit=col[2],
			kiste=col[3],
			nr=col[4]
		)
		
	context= {}
	return render(request, template,context)
	
	
def gallery(request):
	included_extensions = ['jpg','jpeg', 'bmp', 'png', 'gif','JPG','PNG','GIF','JPEG','BMP']
	print(settings.MEDIA_ROOT)
	img_list = [fn for fn in os.listdir(settings.MEDIA_ROOT)
              if any(fn.endswith(ext) for ext in included_extensions)]
	return render(request,'chemie/gallery.html', {'images': img_list})

	
def gallery_delete(request,name):
	if request.method == 'POST':
		name = settings.MEDIA_ROOT + name
		os.remove(name);
		messages.info(request, f"Removed{name}")
	return redirect('chemie-gallery')
	
	
def upload(request):
	context = {}
	if request.method == 'POST':
		uploaded_file = request.FILES['document']
		filename = request.POST.get("nfilename","")
		if len(filename) < 4:
			filename = uploaded_file.name
		messages.success(request, f"filename: {filename}")
		fs = FileSystemStorage()
		name=fs.save(filename,uploaded_file)
		url = fs.url(name)
		context ={'url': url}
		messages.info(request, f"Uploaded {url}")
	return render(request, 'chemie/upload.html',context)
	
def delete_book(request,pk):
	if request.method == 'POST':
		book = Book.objects.get(pk=pk)
		book.delete()
	return redirect('chemie-book-list')
		
def book_list(request):
	books = Book.objects.all()	
	return render(request,'chemie/book_list.html',{
		'books':books
	})

def upload_book(request):
	if request.method == 'POST':
		form = BookForm(request.POST, request.FILES)
		if form.is_valid():
			form.save()
			return redirect('chemie-book-list')
	else:
		form = BookForm()
	return render(request,'chemie/upload_book.html',{
		'form': form
	})
	
def delete_video(request,pk):
	if request.method == 'POST':
		video = Video.objects.get(pk=pk)
		video.delete()
	return redirect('chemie-video-list')
		
def video_list(request):
	videos = Video.objects.all()	
	return render(request,'chemie/video_list.html',{
		'videos':videos
	})
	
def upload_video(request):
	if request.method == 'POST':
		form = VideoForm(request.POST, request.FILES)
		if form.is_valid():
			form.save()
			return redirect('chemie-video-list')
	else:
		form = VideoForm()
	return render(request,'chemie/upload_video.html',{
		'form': form
	})
