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

    PURPOSE::
        This action macro is used to rotate, move to bak or to slide through 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.	Probaly this does work in 1.3.5

    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                    
        2005-08-13 1.3.5-5 RB code change from GET to POST
                              forms instead of link
                              toggle between webnail and image by click on image
                              alias (description) and exif_date added
                              this version needs Gallery2-1.3.5-7.py
        2005-08-31 1.3.5-6 RB html code changed into a function :-)
                                 some html bugs fixed too
                              instead of button text now images used (disabled buttons are grey color coded)
                              back link to callers page
                              whole page inserted into the common wiki page    
                              code clean up.                       
                              
                              
                       

"""
Dependencies = []
import os,string,Image,StringIO
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
from MoinMoin.parser import wiki

def html_show_image(request,pagename,url_wiki_page,full,alias,exif_date,target,idx):

    n = len(target) 
    last_disabled = ''
    last_status = ''
    first_disabled = ''
    first_status = ''
    previous = idx - 1
    next = idx + 1
    
    if idx == n-1 :
       last_disabled = 'disabled'
       last_status = '_disabled'
      
    if idx == 0 :
       first_disabled = 'disabled'
       first_status = '_disabled'
       
       
    if previous < 0 :
        previous = 0
        
    if next > n - 1 :
        next = n - 1
    
    if n == 1 :
        next = 0
      #  previous = 0
      #  first_disabled = 'disabled'
      #  first_status = '_disabled'
      #  last_disabled = 'disabled'
      #  last_status = '_disabled'
    
    html = '''
<table border="1" align="center"">
  <tr align="center" >
     <td>
        <table  border="0";style="border-style:none;">
            <tr align="center">
               
               <form action="%(base_url)s/%(pagename)s" method="POST" enctype="multipart/form-data">
                  <th>   
                     <input type="hidden" name="action" value="gallery2image">
                     <input type="hidden" name="do" value="VS">
                     <input type="hidden" name="full" value="%(first_full_list)s">
                     <input type="hidden" name="alias" value="%(first_alias_list)s">
                     <input type="hidden" name="exif_date" value="%(first_exif_date_list)s">
                     <input type="hidden" name="target" value="%(first_target_list)s">
                     <input type="image" value="submit" src="/wiki/modern/img/first%(first_status)s.png" title="first slide" %(first_disabled)s>
                   </th>  
               </form>
               <form action="%(base_url)s/%(pagename)s" method="POST" enctype="multipart/form-data">
                  <th>
                     <input type="hidden" name="action" value="gallery2image">
                     <input type="hidden" name="do" value="VS">
                     <input type="hidden" name="full" value="%(previous_full_list)s">
                     <input type="hidden" name="alias" value="%(previous_alias_list)s">
                     <input type="hidden" name="exif_date" value="%(previous_exif_date_list)s">
                     <input type="hidden" name="target" value="%(previous_target_list)s">
                     <input type="image" value="submit" src="/wiki/modern/img/previous%(first_status)s.png" title="previous slide" %(first_disabled)s>
                  </th>   
               </form>
               <form action="%(base_url)s/%(pagename)s" method="POST" enctype="multipart/form-data">
                  <th>
                     <input type="hidden" name="action" value="gallery2image">
                     <input type="hidden" name="do" value="VS">
                     <input type="hidden" name="full" value="%(next_full_list)s">
                     <input type="hidden" name="exif_date" value="%(next_exif_date_list)s">
                     <input type="hidden" name="alias" value="%(next_alias_list)s">
                     <input type="hidden" name="target" value="%(next_target_list)s">
                     <input type="image" value="submit" src="/wiki/modern/img/next%(last_status)s.png" title="next slide" %(last_disabled)s>
                  </th>   
               </form>
               <form action="%(base_url)s/%(pagename)s" method="POST" enctype="multipart/form-data">
                  <th>
                     <input type="hidden" name="action" value="gallery2image">
                     <input type="hidden" name="do" value="VS">
                     <input type="hidden" name="full" value="%(last_full_list)s">
                     <input type="hidden" name="alias" value="%(last_alias_list)s">
                     <input type="hidden" name="exif_date" value="%(last_exif_date_list)s">
                     <input type="hidden" name="target" value="%(last_target_list)s">
                     <input type="image" value="submit" src="/wiki/modern/img/last%(last_status)s.png" title="last slide" %(last_disabled)s>
                  </th>   
               </form>
               <form action="%(base_url)s/%(pagename)s" method="POST" enctype="multipart/form-data">
                  <th>
                     <input type="hidden" name="action" value="gallery2image">
                     <input type="hidden" name="do" value="BS">
                     <input type="hidden" name="full" value="%(this_full_list)s">
                     <input type="hidden" name="alias" value="%(this_alias_list)s">
                     <input type="hidden" name="exif_date" value="%(this_exif_date_list)s">
                     <input type="hidden" name="target" value="%(this_target_list)s">
                     <input type="image" value="submit" src="/wiki/modern/img/back.png" title="return to %(pagename)s">
                  </th>   
               </form>
            </tr>
        </table>    
     </td>
  </tr>
  <tr align="center">
     <form action="%(base_url)s/%(pagename)s" method="POST" enctype="multipart/form-data">
         <th>    
            <input type="hidden" name="action" value="gallery2image">
            <input type="hidden" name="do" value="VS">
            <input type="hidden" name="full" value="%(this_target_list)s">
            <input type="hidden" name="alias" value="%(this_alias_list)s">
            <input type="hidden" name="exif_date" value="%(this_exif_date_list)s">
            <input type="hidden" name="target" value="%(this_full_list)s">
            <input type="image" value="submit" src="%(this_image)s">
         </th>
     </form>
  </tr>
  <tr>
     <td>
          <p>
           %(this_alias_text)s
          </p>
     </td>
  </tr>
  <tr>
     <td>
          <p>
             %(this_exif_date_text)s
          </p> 
     </td>
  </tr>

</table>''' % {

"base_url" : request.getScriptname(),
"first_status" : first_status,
"last_status" : last_status,
"first_full_list" : full[0] + "," + string.join(full,','),
"first_alias_list" : alias[0] + '!,!' + string.join(alias,'!,!'),
"first_exif_date_list" : exif_date[0] + ',' + string.join(exif_date,','),
"first_target_list" : target[0] + "," + string.join(target,','),

"previous_full_list" : full[previous] + "," + string.join(full,','),
"previous_alias_list" : alias[previous] + '!,!' + string.join(alias,'!,!'),
"previous_exif_date_list" : exif_date[previous] + ',' + string.join(exif_date,','),
"previous_target_list" : target[previous] + "," + string.join(target,','),

"next_full_list" : full[next] + "," + string.join(full,','),
"next_alias_list" : alias[next] + '!,!' + string.join(alias,'!,!'),
"next_exif_date_list" : exif_date[next] + ',' + string.join(exif_date,','),
"next_target_list" : target[next] + "," + string.join(target,','),

"last_full_list" : full[n-1] + "," + string.join(full,','),
"last_alias_list" : alias[n-1] + '!,!' + string.join(alias,'!,!'),
"last_exif_date_list" : exif_date[n-1] + ',' + string.join(exif_date,','),
"last_target_list" : target[n-1] + "," + string.join(target,','),

"this_full_list" : full[idx] + "," + string.join(full,','),
"this_alias_list" : alias[idx] + '!,!' + string.join(alias,'!,!'),
"this_exif_date_list" : exif_date[idx] + ',' + string.join(exif_date,','),
"this_target_list" : target[idx] + "," + string.join(target,','),

"first_disabled" : first_disabled,
"last_disabled" : last_disabled,
"this_alias_text" : alias[idx],
"this_exif_date_text" : exif_date[idx],
"this_image" : AttachFile.getAttachUrl(pagename,target[idx],request),
"url_wiki_page" : url_wiki_page,
"pagename" : pagename
}


    return html

def to_wikiname(request,text):

    #taken from test_parser_wiki
    page = Page(request, 'ThisPageDoesNotExistsAndWillNeverBeReally')
    page.formatter = Formatter(request)
    request.formatter = page.formatter
    page.formatter.setPage(page)
    page.hilite_re = None
    
    out=StringIO.StringIO()
    request.redirect(out)
    wikiizer = wiki.Parser(text.strip(),request)
    wikiizer.format(page.formatter)
    result = out.getvalue()
    request.redirect()
    del out
    
    return result.strip()


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

def execute(pagename, request):
    """ Main dispatcher for the 'Gallery' action.
    """
    _ = request.getText
    
    request.formatter = Formatter(request)
    attachment_path = AttachFile.getAttachDir(request,pagename)
    if request.form['do'][0] == 'VS' :
        web = {}
        images = string.split(request.form['target'][0],',')
        target = images[0]
        images = (images[1:])
        
        full_image = string.split(request.form['full'][0],',')
        full_target = full_image[0]
        full_image = (full_image[1:])
        
        all_description = string.split(request.form['alias'][0],'!,!')
        this_description = all_description[0]
        all_description = (all_description[1:])
        
        all_exif_date = string.split(request.form['exif_date'][0],',')
        this_exif_date = all_exif_date[0]
        all_exif_date = (all_exif_date[1:])
        
        z = 0
        for img in images :
            if target == img :
               idx = 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.setContentLanguage(request.lang)
        wikiutil.send_title(request, pagename,
                        pagename=pagename)
        request.write(request.formatter.startContent("content"))
        
       
        html = html_show_image(request,pagename,url_wiki_page,full_image,all_description,all_exif_date,images,idx)
        request.write(html)
        request.write(request.formatter.endContent())
        wikiutil.send_footer(request, pagename)
        msg = None
        #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.form['do'][0] == 'BS' :
           
        msg = "gone back" #None
        
    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)s.png" % {"file" : file}
            webnail = "webnail_%(file)s.png" % {"file" : file}
        else:
            img_type="JPEG"
            thumbfile="thumbnail_%(file)s.jpg"  % {"file" : file}
            webnail="webnail_%(file)s.jpg"  % {"file" : file}
 
        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("%(file)s.bak" % {"file" : infile})
            os.link(infile,"%(file)s.bak" % {"file" : infile})
            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()
