
from models import *
from files.models import *
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from oxdjango.decorators import login_required_json
from oxdjango.shortcuts import get_object_or_404_json
try:
  import json
except:
  import simplejson as json
from django.template import Template, Context, RequestContext
from django.template.loader import get_template
from os.path import join
from settings import MEDIA_ROOT, SITE_BASE, UPLOAD_ROOT, PROJECT_PATH
from PIL import Image
import os
from print_pdf import print_url_list
import math
from utils.decorators import user_passes_test_json
import datetime

@login_required
def editor(request):
  user = request.user
  c = Category.objects.all()
  return render_to_response("editor.html", {'categories': c, 'user': user})

def upload(request):
  return render_to_response("upload.html")
'''
def edit_page(request, id):
  page = Page.objects.get(pk=id)
  pageDict = page.get_dict()
  c = Category.objects.all()
  rDict = {
    'categories': c,
    'page': pageDict
    }
'''

"""
  send GET request to to /edit/add_media/ with page_id and resource_id .
"""
@login_required
def add_media(request):
  page_id = request.GET['page_id']
  file_id = request.GET['resource_id']
  page = Page.objects.get(pk=page_id)
  fil = File.objects.get(pk=file_id)
  typ = fil.type
#  typ = Type.objects.get(pk=fil.type_id)
  if typ == 'video':
    try:
      video = Video.objects.get(fil__id=file_id)
      page.videos.add(video)
      page.save()
    except:
      pass
  elif typ == 'audio':
    try:
      audio = Audio.objects.get(fil__id=file_id)
      page.audios.add(audio)
      page.save()
    except:
      pass
  page.save()
  r = {
    'status': 1
    }
  return HttpResponse(simplejson.dumps(r), mimetype="application/json")

@login_required
def add_srt(request):
  file_id = request.POST['id']
  mime = request.POST['mime']
  srt_file = request.FILES['srt']
## REMEMBER TO SAVE SRT FILE!!!##
  if mime == 'video':
    media = Video.objects.get(fil_id=file_id)
  elif mime == 'audio':
    media = Audio.objects.get(fil_id=file_id)
  media.srt.append(srt)
  media.save()
  return HttpResponse("1")

@login_required
def edit_article(request, id):
  c = Category.objects.all()
  a = Article.objects.get(pk=id)
  user = request.user
  if not a.can_edit(user):
    return HttpResponse("sorry, you cannot edit this article. you either do not have permissions, or it is locked.")
  p = a.product
  if p is not None:
    frontend_url = "/edit/article_frontend/%d/%d/" % (p.id, a.order)
  else:
    frontend_url = "/edit/article_web/%d/" % a.id
  rDict = {
    'categories': c,
    'article_id': id,
    'frontend_url': frontend_url,
    'article_width': a.view_size()[0],
    'article_height': a.view_size()[1],
    'rev_no': a.current_revision(),
    'user': request.user
    }
  return render_to_response("editor.html", rDict)    

@login_required
def image_rotate(request, id):
  image_id = int(id)
  if request.GET.has_key('degree'):
    degrees = int(request.GET['degree'])
  else:
    degrees = 0
  image_obj = File.objects.get(pk=image_id)

  
  if ImageBox.objects.filter(file=image_obj).filter(is_displayed=True).count() > 0:
    return HttpResponse("This image is being used on a page. Cannot rotate")
  else:        
    if degrees != 0:
      full_path = MEDIA_ROOT + "/" + image_obj.original_print()
      im = Image.open(full_path).rotate(degrees).save(full_path)
      thumbs = baseFileName(full_path) + "_*"
      cmd = "rm %s" % (thumbs,)
      os.system(cmd)
    path = image_obj.original_print()
    return render_to_response("image_rotate.html", {'path': path, 'id': image_id})  

def testCrop(request):
  d = {
    'path': "images/oldenglish/oepan1.jpg"
    }
  return render_to_response("testCrop.html", d)

@login_required
def imagebox_crop(request):
  o = request.GET
#  project_path = "/home/sanj/soc/edgware-py/"
#  tpl = (int(o['x1']), int(o['y1']), int(o['x2']), int(o['y2']), o['width'], o['height'])
  thisBox = ImageBox.objects.get(pk=o['id'])
  old_value = json.dumps({'path': thisBox.get_path(), 'height': thisBox.height, 'width': thisBox.width})
  thisBox.crop(int(o['x1']), int(o['y1']), int(o['x2']), int(o['y2']), o['width'], o['height'])
  revision_id = saveRevision({
    'user': request.user,
    'box_id': thisBox.id,
    'box_type': 'image',
    'prop': 'image_crop',
    'old_val': old_value,
    'new_val': json.dumps({'path': thisBox.get_path(), 'height': thisBox.height, 'width': thisBox.width}),
    'page_id': thisBox.page.id,
    'uuid': o['uuid']
    })
  r = {
    'path': thisBox.get_path(),
    'rev_id': revision_id
    }  
  return HttpResponse(json.dumps(r), mimetype="application/json")


def test_thumb(request):
  f = File.objects.filter(type__mime__exact='jpg')[0]
  r = {'path': 'media/images/original/facade.jpg'}
  return render_to_response("thumbnailTmp.txt", r)

@login_required
def textbox_new(request):
  if request.GET['json']:
    box = TextBox()
    d = json.loads(request.GET['json'])
    box.html = d['html']
    box.page = Page.objects.get(pk=request.GET['page_id'])
    if d['resource_id'] != 0:
      box.file = File.objects.get(pk=d['resource_id'])
    for c in d['css']:
      prop = c
      val = d['css'][c]
      box.set_css(prop, val)
    box.save()
    revision_id = saveRevision({
      'user': request.user,
      'box_id': box.id,
      'box_type': 'text',
      'prop': 'new_box',
      'old_val': '',
      'new_val': json.dumps(box.to_dict()),
      'page_id': box.page.id,
      'uuid': request.GET['uuid']
      })    
    r = {
      'id': box.id,
      'rev_id': revision_id
      }
    j = json.dumps(r)
    return HttpResponse(j, mimetype="application/json")
  else:
    return False

@login_required    
def textbox_update_css(request):
  box_id = request.GET['id']
  try:
    box = TextBox.objects.get(pk=box_id)
    for c in request.GET:
      if c != 'id' and c != 'uuid':
        prop = c
        val = request.GET[c]
        old_value = box.get_css(prop)
        box.set_css(prop, val)
        revision_id = saveRevision({
          'user': request.user,
          'box_id': box.id,
          'box_type': 'text',
          'prop': prop,
          'old_val': old_value,
          'new_val': val,
          'page_id': box.page.id,
          'uuid': request.GET['uuid']
          })
    box.save()
    r = {
      'status': 1,
      'rev_id': revision_id
      }
  except:
    r = {
      'error': 'Invalid Id: No such box.',
      'status': 0
      }
  j = json.dumps(r)
  return HttpResponse(j, mimetype="application/json")

@login_required
def textbox_set_html(request):
  id = request.GET['id']
  html = request.GET['html']
  box = TextBox.objects.get(pk=id)
  old_value = box.html
  box.html = html
  box.save()
  revision_id = saveRevision({
    'user': request.user,
    'box_id': box.id,
    'box_type': 'text',
    'prop': 'html',
    'old_val': old_value,
    'new_val': html,
    'page_id': box.page.id,
    'uuid': request.GET['uuid']
    })
  r = {
    'status': 1,
    'rev_id': revision_id
    }
  return HttpResponse(json.dumps(r), mimetype="application/json")

@login_required
def textbox_delete(request):
  id = request.GET['id']
  box = TextBox.objects.get(pk=id)
  old_value = json.dumps(box.to_dict())
  box.is_displayed = False
  box.save()
  rev_id = saveRevision({
    'user': request.user,
    'box_id': box.id,
    'box_type': 'text',
    'prop': 'delete_box',
    'old_val': old_value,
    'new_val': '',
    'page_id': box.page.id,
    'uuid': request.GET['uuid']
    })
  return HttpResponse(str(rev_id))

@login_required
def imagebox_new(request):
  jsonString = request.GET['json']
  d = json.loads(jsonString)
  page = Page.objects.get(pk=int(d['page_id']))
  resource = File.objects.get(pk=int(d['resource_id']))  
  box = ImageBox()
  box.file = resource
  box.page = page
  for c in d['css']:
    prop = c
    val = d['css'][c]
    box.set_css(prop, val)
  box.save()
  revision_id = saveRevision({
    'user': request.user,
    'box_id': box.id,
    'box_type': 'image',
    'prop': 'new_box',
    'old_val': '',
    'new_val': json.dumps(box.to_dict(1)),
    'page_id': box.page.id,
    'uuid': request.GET['uuid']
    })
  r = {
    'id': box.id,
    'rev_id': revision_id,
    'status': 1
    }
  j = json.dumps(r)
  return HttpResponse(j, mimetype="application/json")

@login_required
def imagebox_update_css(request):
  box_id = request.GET['id']
  box = ImageBox.objects.get(pk = box_id)
  for c in request.GET:
    if c != 'id' and c!= 'uuid':
      prop = c
      val = request.GET[c]
      old_value = box.get_css(prop)
      box.set_css(prop, val)
      revision_id = saveRevision({
        'user': request.user,
        'box_id': box.id,
        'box_type': 'image',
        'prop': prop,
        'old_val': old_value,
        'new_val': val,
        'page_id': box.page.id,
        'uuid': request.GET['uuid']
        })
  box.save()
  r = {
    'status': 1,
    'id': box.id,
    'rev_id': revision_id
    }
  j = json.dumps(r)
  return HttpResponse(j, mimetype="application/json")

@login_required
def imagebox_resize(request):
  box_id = request.GET['id']
  width = request.GET['width']
  height = request.GET['height']
  box = ImageBox.objects.get(pk = box_id)
  old_value = json.dumps({
    'path': box.get_path(),
    'width': box.width,
    'height': box.height
    })
  box.resize(width, height)
  box.set_css('width', width)
  box.set_css('height', height)
  box.save()
  resizedPath = box.get_path()
  revision_id = saveRevision({
    'user': request.user,
    'box_id': box.id,
    'box_type': 'image',
    'prop': 'image_resize',
    'old_val': old_value,
    'new_val': json.dumps({
      'path': box.get_path(),
      'width': width,
      'height': height
      }),   
    'page_id': box.page.id,
    'uuid': request.GET['uuid']
    })
  r = {
    'status': 1,
    'path': resizedPath,
    'rev_id': revision_id
    }
  j = json.dumps(r)
  return HttpResponse(j, mimetype="application/json")

@login_required
def imagebox_delete(request):
  id = request.GET['id']
  box = ImageBox.objects.get(pk=id)
  old_value = json.dumps(box.to_dict(1))
  box.is_displayed = False
  box.save()
  rev_id = saveRevision({
    'user': request.user,
    'box_id': box.id,
    'box_type': 'image',
    'prop': 'delete_box',
    'old_val': old_value,
    'new_val': '',
    'page_id': box.page.id,
    'uuid': request.GET['uuid']
    })
  return HttpResponse(str(rev_id))

def category_json(request):
  if request.GET:
    catid = request.GET['id']
    typ = request.GET.get('type', 'image')
    resources = File.objects.filter(categories__id=catid, type=typ)
    rList = []
    for r in resources:
      # these should not be here
      width = 0
      height = 0
      if r.type == 'image':
        filePath = r.original_print()
        try:
          fil = Image.open(join(MEDIA_ROOT, filePath))
          TARGET_WIDTH = 320
          width = TARGET_WIDTH
          orig_size = fil.size;
          aspect_ratio = orig_size[1] / (orig_size[0] + .0)
          height = TARGET_WIDTH * aspect_ratio
          output_size = (TARGET_WIDTH, int(height),)
          f = open(join(MEDIA_ROOT, filePath))
          iconSize = "100x100"
          resizedSize = str(TARGET_WIDTH) + "x" + str(int(height))
#          context = {'path': filePath, 'size': (100,100,)}
#          context2 = {'path': filePath, 'size': output_size}
          iconPath = get_thumbnail(f, iconSize, crop="center", quality=99).url
          resizedPath = get_thumbnail(f, resizedSize, quality=99).url
        except:
          iconPath = "/static/images/binimages/jpg.jpg"
          resizedPath = filePath
      else:
        filePath = r.file.url.replace(PROJECT_PATH, "") #FIXME: Why does file.url return system path and not relative URL??
        iconPath = "/static/images/binimages/%s.jpg" % (r.type)
        resizedPath = filePath
      if r.type == 'video':
        try:
          v = Video.objects.filter(fil=r)[0]
          media_id = v.id
        except:
          media_id = 0
      elif r.type == 'audio':
        try:
          a = Audio.objects.filter(fil=r)[0]
          media_id = a.id
        except:
          media_id = 0
      else:
        media_id = 0
          
      if r.description == '':
        description = r.full_path.replace(UPLOAD_ROOT, "")
      else:
        description = r.description
      d = {
        'id': r.id,
        'type': r.type,
        'title': r.title,
        'file': filePath,
        'description': description,
        'tags': r.tags,
        'icon': iconPath,
        'width': width,
        'height': int(height),
        'resized': resizedPath,
        'added': str(r.added),
        'mime': r.type,
        'media_id': media_id
        }
      rList.append(d)
    j = json.dumps({'resources': rList})
    return HttpResponse(j, mimetype="application/json")
  else:
    return False

def canvas_save(request):
  j1 = request.GET['json']
  id = request.GET['id']
  d = json.loads(j1)
  canvas = Page.objects.get(pk=id)
  canvas.save_from_dict(d)
  json2 = json.dumps(d)
  return HttpResponse(json2)

'''
Not using this views after all ... but maybe, just maybe, they were a good idea ...
def save_revision(request):
  page_id = request.GET['page_id']
  page = Page.objects.get(pk = page_id)
  page.save_revision()
  return HttpResponse("1")

def load_revision(request):
  page_id = request.GET['page_id']
  page = Page.objects.get(pk = page_id)
  rev_no = request.GET['rev_no']
  json = page.load_revision(rev_no)
#FIXME: Return Json with its proper mime-type, etc.
  return HttpResponse(json)
'''

def get_page_json(request, issue_no, page_no):
#FIXME: There's got to be a better way to get the page based on issue no. and page no. (OR, pass the page id somehow, but the URL's look prettier if its /issue_no/page_no . Alternatively, at least make getPage() a function somewhere.
  page = Page.objects.filter(issue__issue_no = issue_no).filter(page_no = page_no)[0]
  d = page.get_dict()
  json = json.dumps(d)
  return HttpResponse(json)

def view_page(request, id):
  """
  View for the actual front-end view of the page
  """
  id = int(id)
  page = Page.objects.get(pk=id)
  d = page.get_dict(1)
  return render_to_response("view_page.html", d)

def view_article(request, id):
  if request.GET.has_key('m'):
    m = float(request.GET['m'])
  else:
    m = 1
  id = int(id)
  article = Article.objects.get(pk=id)
  if request.GET.has_key('p'):
    p = int(request.GET['p'])
    d = article.get_dict(m, p)
  else:
    d = article.get_dict(m)
  page_width = article.view_size()[0]
  page_height = article.view_size()[1]
  return render_to_response("view_article.html", {'pages': d, 'm': m, 'width': addPx(page_width), 'height': addPx(page_height)})


@login_required
def articleTitle(request):
  user = request.user
  id = request.POST.get("id", "0")
  article = Article.objects.get(pk=id)
  if not article.is_owner(user):
    return HttpResponse("sorry, you do not have permission to do that.")
  oldTitle = article.name
  title = request.POST.get("title", oldTitle)
  article.name = title
  article.save()
  return HttpResponse("title edited. thanks.")

@login_required
def lockArticle(request):
  user = request.user
  id = request.POST.get("id", "0")
  article = Article.objects.get(pk=id)
  if not article.is_owner(user):
    return HttpResponse("sorry, you do not have permission to do that.")
  locked = request.POST.get("locked", "false")
  if locked == "true":
    article.locked = True
    msg = "article locked. it will no longer be editable on the tool page."
  else:
    article.locked = False
    msg = "article unlocked."
  article.save()
  return HttpResponse(msg)

@login_required
def publishArticle(request):
  user = request.user
  id = request.POST.get("id", "0")
  article = Article.objects.get(pk=id)
  if not article.is_owner(user):
    return HttpResponse("sorry, you do not have permission to do that.")
  published = request.POST.get("published", "false")
  if published == "true":
    article.published = True
    if article.published_date == None:
      article.published_date = datetime.datetime.now()
    msg = "article published. it will now be browsable on public pages."
  else:
    article.published = False
    msg = "article unpublished. it will no longer be browsable on public pages."
  article.save()
  return HttpResponse(msg)



@login_required
def create_article(request):
  if request.POST:
    template_article = int(request.POST['article_id'])
    new_name = request.POST['article_name']
    t = Article.objects.get(pk=template_article)
    new_article = t.get_copy()
    new_article.name = new_name
    new_article.owner = request.user
    new_article.save()
    new_id = new_article.id
    return HttpResponse("/edit/article/%d/" % new_id)

  else:
    templates = []
    others = []
    for a in Article.objects.all():
      if a.name.upper().startswith('TEMPLATE'):
        templates.append(a)
      else:
        others.append(a)
    return render_to_response("create_article.html", {'templates': templates, 'others': others})


def articlesByTheme(request):
  user = request.user
  theme_id = request.GET.get("theme_id", "0")
  article_list = Article.get_theme_list(theme_id)
  articles = []
  for article in article_list:
    articles.append(article.get_list_dict(user))
  return HttpResponse(json.dumps(articles), mimetype="application/javascript")


def article_frontend(request, product_id, article_order):
  product = Product.objects.get(pk=product_id)
  article = Article.objects.filter(product=product, order=article_order)[0]
  width = product.get_view_size()[0]
  height = product.get_view_size()[1]
  pages = article.get_dict()
  articles_before = Article.objects.filter(product=product, order__lt=article_order).order_by('order')
  articles_after = Article.objects.filter(product=product, order__gt=article_order).order_by('order')
  d = {
    'pages': pages,
    'height': height,
    'width': width,
    'm': 1,
    'article': article,
    'articles_before': articles_before,
    'articles_after': articles_after
  }
  return render_to_response("article_frontend.html", {'pages': pages, 'width': width, 'height': height, 'm': 1})

def article_webalone(request, article_id):
  article = Article.objects.get(pk=article_id)
  user = request.user
  if not article.can_view(user):
    return HttpResponse("sorry, you do not have the permissions to view this article")
  width = article.view_size()[0]
  height = article.view_size()[1]
  pages = article.get_dict()
  articles_before = []
  articles_after = []
  d = {
    'pages': pages,
    'height': height,
    'width': width,
    'm': 1,
    'locked': article.locked,
    'published': article.published,
    'is_owner': article.is_owner(user),
    'article': article,
    'articles_before': [],
    'articles_after': []
  }
  d = RequestContext(request, d)
  return render_to_response("article_frontend.html", d)

def poll_changes(request):
  a_id = request.GET['article_id']
  article = Article.objects.get(pk=a_id)
  rev_no = request.GET['rev_no']
  uuid = request.GET['uuid']
  changes = article.changes(rev_no, uuid)
  
  return HttpResponse(json.dumps(changes), mimetype="application/javascript")
    
def page_pdf(request):
  article_id = request.GET['a']
  page_id = request.GET['p']
  if request.GET.has_key('dpi'):
    dpi = request.GET['dpi']
  else:
    dpi = 150
  if request.GET.has_key('m'):
    m = request.GET['m']
  else:
    article = Article.objects.get(pk=article_id)
    m = article.get_print_multiplier(dpi)
  print_width_mm = article.product.typ.print_width
  print_height_mm = int(print_width_mm // article.product.typ.aspect_ratio)
  output_path = MEDIA_ROOT + "/pdf/tmpPDF" + article_id + page_id + ".pdf"
  cmd = "wkhtmltopdf --page-width %d --page-height %d '%s/edit/view_article/%s/?m=%f&p=%s' '%s'" % (print_width_mm, print_height_mm, SITE_BASE, article_id, m, page_id,output_path,)
  os.system(cmd)
  return HttpResponseRedirect(output_path.replace(MEDIA_ROOT, "/static"))

'''
def article_pdf(request):
  article_id = request.GET['a']
  page_links = []
  article = get_object_or_404_json(Article, pk=article_id)
  pages = Page.objects.filter(article=article)
'''

def product_pdf(request):
  p_id = request.GET['id']
  product = get_object_or_404_json(Product, pk=p_id)
  if request.GET.has_key('dpi'):
    dpi = request.GET['dpi']
  else:
    dpi = 150
  if request.GET.has_key('width'):
    width_mm = request.GET['width']
  else:
    width_mm = product.typ.print_width
  height_mm = int(round(width_mm // product.typ.aspect_ratio))
  pages = product.get_page_list()
  m = product.get_print_multiplier(dpi)
  url_list = []
  for p in pages:
    url = SITE_BASE + "/edit/view_article/%d/?m=%f'" % (p.article.id, m)
    url_list.append(url)
  output_path = MEDIA_ROOT + "/pdf/" + product.title + ".pdf"
  pdf_path = print_url_list(url_list, width_mm, height_mm, output_path)
  return HttpResponseRedirect(pdf_path.replace(MEDIA_ROOT, "/static"))

def article_pdf(request):
  a_id = request.GET['id']
  article = get_object_or_404_json(Article, pk=a_id)
  dpi = request.GET.get('dpi', 600)
  width_mm = request.GET.get('width', article.typ.print_width)
  height_mm = math.ceil(width_mm / article.typ.aspect_ratio)
  pages = Page.objects.filter(article=article).order_by('page_no')
  m = article.get_print_multiplier(dpi)
  url = SITE_BASE + "/edit/view_article/%d/?m=%f" % (article.id, m)
  url_list = [url]
  '''  
  url_list = []
  for p in pages:
    url = SITE_BASE + "/edit/view_article/%d/?m=%f&p=%d" % (article.id, m, p.id)
    url_list.append(url)
  '''
  output_path = MEDIA_ROOT + "/pdf/" + article.name + "_" + str(article.current_revision()) + ".pdf"
  pdf_path = print_url_list(url_list, width_mm, height_mm, dpi, output_path)   
  return HttpResponseRedirect(pdf_path.replace(MEDIA_ROOT, "/static"))

def article_json(request):
  article_id = request.GET['id']
  article = Article.objects.get(pk=article_id)
  d = article.get_dict()
  j = json.dumps(d)
  return HttpResponse(j, mimetype="application/json")

def new_page(request):
  article = Article.objects.get(pk=request.GET['article_id'])
  p = Page()
  p.article = article
  try:
    last_page = Page.objects.filter(article=article).order_by('-page_no')[0]
    last_page_no = last_page.page_no
  except:
    last_page_no = 0
  p.page_no = last_page_no + 1
  p.save()
  rev_id = saveRevision({
    'user': request.user,
    'box_id': 0,
    'box_type': 'page',
    'prop': 'new_page',
    'old_val': 0,
    'new_val': json.dumps(p.get_dict(1)),
    'page_id': p.id,
    'uuid': request.GET['uuid']
    })
  r = {
    'id': p.id,
    'rev_id': rev_id
    }
  return HttpResponse(json.dumps(r), mimetype="application/json")

@login_required_json
def delete_page(request):
  page = get_object_or_404_json(Page, id=request.GET['id'])
  page_id = page.id
  page.delete()
  rev_id = saveRevision({
    'user': request.user,
    'box_id': 0,
    'box_type': 'page',
    'prop': 'delete_page',
    'old_val': page.get_dict(1),
    'new_val': page_id,
    'uuid': request.GET['uuid']
    })
  r = {
    'rev_id': rev_id
    }
  return HttpResponse(json.dumps(r), mimetype="application/json")  


@login_required_json
def move_page(request):
  page = get_object_or_404_json(Page, id=request.GET['id'])
  current_no = page.page_no
  new_no = request.GET['new_order']
  page.set_page_no(new_no)
  rev_id = saveRevision({
    'user': request.user,
    'page_id': page.id,
    'box_id': page.id,
    'box_type': 'page',
    'prop': 'move_page',
    'old_val': current_no,
    'new_val': new_no,
    'uuid': request.GET['uuid']
  })
  r = {
    'rev_id': rev_id
  }
  return HttpResponse(json.dumps(r), mimetype="application/json")


def product_list(request):
  products = Product.objects.all()
  return render_to_response("product_list.html", {'products': products})

def article_list(request):
  articles = Article.objects.all()
  return render_to_response("article_list.html", {'articles': articles})

def new_issue(request):
  name = request.GET['issueName']
  last_issue_no = Issue.objects.all().order_by('-issue_no')[0].issue_no
  issue_no = last_issue_no + 1
  i = Issue(title = name, issue_no = issue_no)
  i.save()
  return HttpResponse("saved")

def edit_issue(request, id):
  i = Issue.objects.get(pk=id)
  return render_to_response

def edit_product(request, id):
  p = Product.objects.get(pk=id)
  articles = Article.objects.filter(product=p)
  return render_to_response("article_list.html", {'product': p, 'articles': articles})

"""
These are some views that I could think of that need to be created. Please add more.

def new_text_box(request):
  return box_id

def new_image_box(request):
  return box_id

def edit_page(request, issue, page):
  
def publish_issue(request):

"""

def show_slide(request, id):
  img = SliderImage.objects.get(pk=id)
  if request.GET.has_key('c'):
    hasCommented = True
  else:
    hasCommented = False
  try:
    prevImage = SliderImage.objects.filter(id__lt=id).order_by('-id')[0]
    hasPrev = prevImage.id
  except:
    hasPrev = False
  try:
    nextImage = SliderImage.objects.filter(id__gt=id)[0]
    hasNext = nextImage.id
  except:
    hasNext = False
  d = {
    'img': img,
    'hasPrev': hasPrev,
    'hasNext': hasNext,
    'hasCommented': hasCommented
    }
  return render_to_response("slider.html", d)

def show_slide2(request):
  img = SliderImage.objects.get(pk=1)
  hasPrev = False
  nextImage = SliderImage.objects.filter(id__gt=1)[0]
  hasNext = nextImage.id
  d = {
    'img': img,
    'hasPrev': hasPrev,
    'hasNext': hasNext
    }
  return render_to_response("slider.html", d)


