# 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

'''
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)

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")

@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')

