# -*- coding: iso-8859-1 -*-
"""
    MoinMoin - gallery2Image Actionmacro

    PURPOSE:
        This action macro is used to rotate the images from Gallery2

    CALLING SEQUENCE:
        called by Gallery2 POST Method

    PROCEDURE:
        see Gallery2

        Please remove the version number from this file

    RESTRICTIONS:
        spaces in file names are not supported. I don't know how to escape them right.	

    MODIFICATION HISTORY:
        Version 1.3.3.-1
        @copyright: 2005 by Reimar Bauer (R.Bauer@fz-juelich.de)
        @license: GNU GPL, see COPYING for details.
        2005-06-24: 1.3.3.-2 feature reqeust of CraigJohnson added 
                             os.path.join used to join platform independent pathes 
                             os.unlink removed to get it more platform independend
        2005-08-06: 1.3.5-3 RB VS mode added 
                            by one step back or forward could be toggled through the selected slides
                            and the first and last one could be selected too
        2005-08-07 1.3.5-4 RB bug fixed for cgi-bin call. formatting of tables adjusted                    


"""
Dependencies = []
import os,string,Image
from MoinMoin import config, wikiutil
from MoinMoin.PageEditor import PageEditor
from MoinMoin import user, util
from MoinMoin.Page import Page
from MoinMoin.action import AttachFile
from MoinMoin.formatter.text_html import Formatter

action_name = __name__.split('.')[-1]

def execute(pagename, request):
    """ Main dispatcher for the 'Gallery' action.
    """
    _ = request.getText
    
    request.formatter = Formatter(request)
    if(request.form['do'][0] == 'VS'):
        web={}
        images=string.split(request.form['target'][0],',')
        target=images[0]
        images=(images[1:])
        z=0
        for img in images :
            if (target == img):
               previous=z-1
               next=z+1
      
            z=z+1
        n=len(images)

        ######## url_wiki_page #############################################################
        text=pagename
        url=pagename
        url_wiki_page=wikiutil.link_tag(request, url, text=text,
                                   formatter=request.formatter)   
        ############################################################################			 

        attachment_path = AttachFile.getAttachDir(request,pagename)

        web['src']=AttachFile.getAttachUrl(pagename,target,request)
        web['title']=target
        #web['width']="1024"
        

        image_link=request.formatter.image(**web)
        
       
        request.http_headers()
        
        request.write('<html>')
        request.write('<head>')
        request.write('<meta http-equiv="Content-Type" content="text/html;charset=utf-8">')
        request.write('<meta name="robots" content="noindex,nofollow">')
     

        request.write("<H2>%(pagename)s</H2>" % {
                      "pagename":url_wiki_page})
      

        request.write("<TABLE BORDER=1 ALIGN=CENTER><TR><TD>")
        
        if (previous >= 0):
            webn_url="%(pagename)s?action=gallery2image&do=VS&target=%(webnail)s" % {
                     "pagename":pagename,
                     "webnail":images[0]+","+string.join(images,',')}
            text='FIRST'
            url=webn_url
            first_img=wikiutil.link_tag(request, url, text=text,
                                   formatter=request.formatter)   

            request.write("<TABLE ALIGN=LEFT><TR><TD>%(INPUT)s</TD></TR></TABLE> " % {
                          "INPUT":first_img})

        if (next < n):  
            webn_url="%(pagename)s?action=gallery2image&do=VS&target=%(webnail)s" % {
                     "pagename":pagename,
                     "webnail":images[n-1]+","+string.join(images,',')}
            text='LAST'
            url=webn_url
            last_img=wikiutil.link_tag(request, url, text=text,
                                   formatter=request.formatter)   

            request.write("<TABLE ALIGN=RIGHT><TR><TD>%(INPUT)s</TD></TR></TABLE> " % {
                          "INPUT":last_img})

        if (n > 1):
            request.write("<TABLE  ALIGN=CENTER><TR>")

            if (previous >= 0):
                webn_url="%(pagename)s?action=gallery2image&do=VS&target=%(webnail)s" % {
                         "pagename":pagename,
                         "webnail":images[previous]+","+string.join(images,',')}
                text='PREVIOUS'
                url=webn_url
                previous_img=wikiutil.link_tag(request, url, text=text,
                                               formatter=request.formatter)   

                request.write("<TD>%(INPUT)s</TD>" % {
                              "INPUT":previous_img})
  
            if (next < n):   
                webn_url="%(pagename)s?action=gallery2image&do=VS&target=%(webnail)s" % {
                         "pagename":pagename,
                         "webnail":images[next]+","+string.join(images,',')}
                text='NEXT'
                url=webn_url
                next_img=wikiutil.link_tag(request, url, text=text,
                                           formatter=request.formatter)   

                request.write("<TD>%(INPUT)s</TD>" % {
                              "INPUT":next_img})
  

            request.write("</TR></TABLE>")
        request.write(image_link)
        request.write("</TD></TR>")
        request.write("<TR><TD>")
        request.write("back to %(url_wiki_page)s" % {
                      "url_wiki_page":url_wiki_page})  
      
        request.write("</TD></TR></TABLE>")	    
        request.write("</HTML>")
        
        return
        
    elif(request.form['do'][0] == 'PS'):
            images=string.split(request.form['target'][0],',')
            attachment_path = AttachFile.getAttachDir(request,pagename)
            target=request.form['target'][0]

            msg= _('not finished by now') #+ target

    elif request.user.may.delete(pagename):
       # only users which are allowed to delete should use this tool

        target=request.form['target'][0]
        file, ext = os.path.splitext(target)

        if (ext == '.gif') or (ext == '.png'):
            img_type='PNG'
            thumbfile='thumbnail_'+file+".png"
            webnail='webnail_'+file+".png"
        else:
            img_type="JPEG"
            thumbfile='thumbnail_'+file+".jpg"
            webnail='webnail_'+file+".jpg"


        attachment_path = AttachFile.getAttachDir(request,pagename)
        thumb=os.path.join(attachment_path,thumbfile)
        webf=os.path.join(attachment_path,webnail)
        infile=os.path.join(attachment_path,target)

        msg = None
        if action_name in request.cfg.excluded_actions:
            msg = _('File attachments are not allowed in this wiki!')

        elif (request.form['do'][0] == 'RM'):
            if os.path.exists(infile+'.bak'):
               os.unlink(infile+'.bak')
            os.link(infile,infile+'.bak')
            os.unlink(infile)
            os.unlink(webf)
            os.unlink(thumb)

            msg= _('%(target)s deleted, backup in place' % {
                  'target':target})

        elif (request.form['do'][0] == 'RL'):
            im = Image.open(infile)
            #os.unlink(infile)
            im.rotate(90).save(infile,img_type)
            nim = Image.open(infile)
            nim.thumbnail((640,640), Image.ANTIALIAS)
            #os.unlink(webf)
            nim.save(webf, img_type)
            nim.thumbnail((128, 128), Image.ANTIALIAS)
            #os.unlink(thumb)
            nim.save(thumb, img_type)
            msg= _('%(target)s rotated to left 90 degrees' % {
                  'target':target})

        elif (request.form['do'][0] == 'RR'):
            im = Image.open(infile)
            #os.unlink(infile)
            im.rotate(270).save(infile,img_type)


            nim = Image.open(infile)

            nim.thumbnail((640,640), Image.ANTIALIAS)
            #os.unlink(webf)
            nim.save(webf, img_type)
            nim.thumbnail((128, 128), Image.ANTIALIAS)
            #os.unlink(thumb)
            nim.save(thumb, img_type)
            msg= _('%(target)s rotated to right 90 degrees' % {
                  'target':target})

        else:
            msg = _('action not implemented: %s') % (request.form['do'][0],)
    else:
        msg = _('Your are not allowed to change images on this page: %s') % (pagename,)

    if msg:
        AttachFile.error_msg(pagename, request, msg)

    return()
