# Create your views here.
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django import forms
from models import Category, File
from settings import FTP_ROOT, UPLOAD_ROOT
import os
from os.path import join, isdir, getmtime, basename
import shutil
from django.views.decorators.csrf import csrf_exempt
from ox.django.shortcuts import render_to_json_response
from django.shortcuts import get_object_or_404
from models import TYPE_CHOICES
from django.core.paginator import Paginator, InvalidPage, EmptyPage

'''
class folder_names(object):      
  def __iter__(self):
    return iter(map(lambda x: (x,x), os.listdir(UPLOAD_ROOT)))
'''

def getFolderList():
  os.chdir(FTP_ROOT)
  dirs = filter(isdir, os.listdir(FTP_ROOT))
  full_dirs = [join(FTP_ROOT, d) for d in dirs]  
  full_dirs.sort(key=lambda x: getmtime(x), reverse=True)
  return map(lambda x: (basename(x), basename(x)), full_dirs)

@login_required
def upload_files(request):  
  return render_to_response("upload_files.html", {
    'categoryForm': CategoryForm()
  })

@login_required
def add_category(request):
  category_id = request.GET['category_id']
  try:
    c = Category.objects.get(pk=category_id)
  except:
    category_name = request.GET['category_name']
    if category_name != '':
      try:
        c = Category.objects.get(name=category_name)
      except:
        c = Category()
        c.name = category_name
        c.save()
  return render_to_json_response({'category_id': c.id, 'category_name': c.name})

class FolderSelect(forms.widgets.Select):
  def _get_choices(self):
    return getFolderList()
#    return map(lambda x: (x,x), os.listdir(UPLOAD_ROOT)) 

  def _set_choices(self, value):
    self._choices = value

  choices = property(_get_choices, _set_choices)


 
class FolderField(forms.ChoiceField):
  widget = FolderSelect

  def _get_choices(self):
    return getFolderList()
#    return map(lambda x: (x,x), os.listdir(UPLOAD_ROOT))   


class AddFolderForm(forms.Form):
  folder_name = FolderField(label="Name of Folder", choices=getFolderList())
  category = forms.ModelChoiceField(Category.objects, required=False, label="Study")
  category_name = forms.CharField(required=False, label="Create New Study")

class CategoryForm(forms.Form):
  category = forms.ModelChoiceField(Category.objects, required=False, label="Study")
  category_name = forms.CharField(required=False, label="Create New Study")

class FileFilterForm(forms.Form):
  category = forms.ModelChoiceField(Category.objects, required=False, label="Study")
  fileType = forms.ChoiceField(TYPE_CHOICES, required=False, label="File Type")
  search = forms.CharField(required=False)

@login_required
def add_folder(request):
  if request.POST:
    form = AddFolderForm(request.POST)
    if form.is_valid():
      folder_name = form.cleaned_data['folder_name']
      category = form.cleaned_data['category']
      if not category:
        category_name = form.cleaned_data['category_name']
        category = Category(name=category_name)
        category.save()
      user = request.user
#      import pdb;pdb.set_trace()
      n = 1
      while os.path.exists(join(UPLOAD_ROOT, folder_name)):
        n += 1
        folder_name = u'%s (%s)' % (form.cleaned_data['folder_name'], n)
      shutil.move(join(FTP_ROOT, folder_name), UPLOAD_ROOT)
      File.addFiles(category, user, folder_name)
      return render_to_response("files/added_folder.html", {
        'folder_name': folder_name,
        'category_name': category.name,
        'username': user.username
        })
    else:
      return render_to_response("files/add_folder.html", {'form': form})
  else:
    form = AddFolderForm()
  return render_to_response("files/add_folder.html", {'form': form})  

def editor(request):
  return render_to_response("editor.html")

'''
def gallery(request):
  return HttpResponseRedirect('http://www.urbaanedge.com/wordpress')
'''

#Start Upload stuff - from hostb.org/host/views.py

class ChunkForm(forms.Form):
    chunk = forms.FileField()
    done = forms.IntegerField(required=False)

@csrf_exempt
def chunk(request, id):
    if request.method == 'POST':
        item = get_object_or_404(File, id=id)
        form = ChunkForm(request.POST, request.FILES)
        canEdit = True
        if form.is_valid() and canEdit:
            f = form.cleaned_data['chunk']
            response = {
                'resultUrl': '/files/' + str(item.id),
                'fileId': item.id
            }
            if item.title:
                name = item.title
            else:
                name = f.name
            if not item.save_chunk(f.read(), name):
                response['result'] = 'failed'
            elif form.cleaned_data['done']:
                item.done = True
                item.save()
                response['done'] = 1
                response['result'] = 1
            else:
                response['result'] = 1
            return render_to_json_response(response)
    response = {
        'result': -1,
        'fileUrl': '/'
    }
    return render_to_json_response(response)

@csrf_exempt
def add(request):
    if request.method == 'POST':
        if request.POST.get('firefogg', False):
            file = File()
            file.userID = request.user
            file.info = '' #WTF!       
            file.title = request.POST.get('name', '')
            file.save()
            category_id = request.POST.get('category', 1)
            c = Category.objects.get(pk=category_id)
            file.categories.add(c)
            file.save()
            response = {
                'result': 1,
                'maxRetry': 10,
                'uploadUrl': '/files/' + str(file.id) + "/chunk"
#                'uploadUrl': request.build_absolute_uri("%s/chunk" % file.get_absolute_url())
            }
            return render_to_json_response(response)
        # Save any files that were uploaded (ignoring empty form fields)
        if 'file' in request.FILES:
            new_file = request.FILES['file']
            file = File(title=new_file.name)
            file.userID = request.user
            file.done = True
            file.info = '' #WTF!
            file.file.save(new_file.name, new_file)
            file.save()
            if request.POST.get('api', False):
                return HttpResponse(request.build_absolute_uri(file.get_absolute_url()), content_type="text/plain")
            return HttpResponseRedirect(file.get_absolute_url())

    #no upload
    return HttpResponseRedirect('/')


@csrf_exempt
@login_required
def editFile(request):
  errors = []
  try:
    id = request.POST['id']
    fil = File.objects.get(pk=id)
  except:
    errors.append("Invalid File ID")
  keys = ['title', 'description', 'tags']
  for k in keys:
    val = request.POST[k]
    fil.__setattr__(k, val)
  fil.save()
  response = {
    'errors': errors
  }
  return render_to_json_response(response)


@csrf_exempt
@login_required
def deleteFile(request):
  errors = []
  try:
    id = request.POST['id']
    fil = File.objects.get(pk=id)
  except:
    errors.append("Invalid File ID")
  fil.delete()
  response = {
    'errors': errors
  }
  return render_to_json_response(response)

@csrf_exempt
def fileList(request):
  category = request.POST.get("category", '')
  typ = request.POST.get("fileType", '')
  search = request.POST.get("search", '')
  page = request.POST.get("page_no", 1)
  qset = File.objects.all()
  if category != '':
    qset = File.filter_category(category, qset)
  if typ != '':
    qset = File.filter_type(typ, qset)
  if search != '':
    qset = File.fts(search, qset)
  RESULTS_PER_PAGE = 20
  paginator = Paginator(qset, RESULTS_PER_PAGE)  
  try:
    results = paginator.page(page)
  except (EmptyPage, InvalidPage):
    results = paginator.page(paginator.num_pages)
  files = results.object_list
  d = {}
  d['noOfResults'] = qset.count()
  d['noOfPages'] = paginator.num_pages
#  d['hasPrev'] = paginator.has_previous()
#  d['hasNext'] = paginator.has_next()
  d['files'] = []
  for f in files:
    d['files'].append(f.get_dict())
  return render_to_json_response(d)

def browse(request):
  form = FileFilterForm()
  return render_to_response("files/browser.html", {
    'filterForm': form
  })

