# -*- coding: iso-8859-1 -*-
"""
    MoinMoin - gallery2Image Action macro

    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
        
        slide show is best used with fastcgi if you have many images

    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.       
        2005-09-01 1.3.5-7 RB image paths changed to absoulte url
        2005-10-29 1.3.5-8 RB the code of VS rewritten
                              for the slideshow changed to a javascript player learned from Ricocheting
                              image preloading for webnails and fullimages because webspeed could be slow
                              slide show is really fast by this
                              default duration is 1000msec
                              (runs under 1.5.0 too)
        2005-11-01 1.3.5-9 RB output buttons changed to <SPAN id> text 
                              to all javascript functions added the prefix gallery2
                              some fixes on javascript code
                              controls separated.
       2005-11-12 1.3.5-10 RB alias text is displayed by innerHTML                       
                              bug fixed ' is allowed to use in alias text 
                              wish of grey out buttons for first or last slide button added 
                              span id's changed to a prefix of gallery2_
       2005-11-25 1.3.5-11 RB bug fixed of selecting an index of a scalar value                        
                              (It's a python wonder that it has worked this way)
       2005-01-27 1.5.1-12 RB switch of release number to MoinMoin Version 1.5 
                              duplicated call of html tag body and head removed
                                                         
                       

"""
Dependencies = []
import os,string,Image,StringIO
from MoinMoin import config, wikiutil, version
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 option_list(this_image,pagename,text,request):
    txt = ''
   
    for s in text:
        name = AttachFile.getAttachUrl(pagename,s,request)
        if name == this_image:
            txt += '<option selected value="%(name)s">%(alias)s' % {
                "name":name,
                "alias":s} 
            
        else:   
            txt += '<option value="%(name)s">%(alias)s' % {
                "name":name,
                "alias":s}
                
    return txt
    
def to_htmltext(text):        
  
    if text.find ("'"):   
        text = text.split("'")
        text = '&#39;'.join(text)
       
    return text

def html_js(this_image,counter):    
   html = '''
<SCRIPT LANGUAGE="JavaScript">
<!-- Original:  Ricocheting (ricocheting@hotmail.com) -->
<!-- Web Site:  http://www.ricocheting.com -->

<!-- This script and many more are available free online at -->
<!-- The JavaScript Source!! http://javascript.internet.com -->

<!-- Modifications by Reimar Bauer <R.Bauer@fz-juelich.de> -->
<!-- 2005-10-29 -->
<!-- Many thanks to Ricocheting, it is much easier as my own one. I like it -->
<!-- Some code added and replaced for the MoinMoin:Gallery2 parser-->


<!-- Begin 

var rotate_delay = 1000; // delay in milliseconds (5000 = 5 secs)
var current = %(counter)s;
var theImages = new Array();
var thewebImages =  new Array();
var thefullImages =  new Array();

function gallery2preload() {
   var list = document.slideform.webnail_list.value;
   var value = list.split(","); 
   var n = value.length;
   
   for (i = 0; i <  n-1; i++){
       theImages[i] = new Image();
       theImages[i].src = value[i];
   }   
   thewebImages = theImages;
   
   var list = document.slideform.full_list.value;
   var value = list.split(","); 
   var n = value.length;
   
   for (i = 0; i <  n-1; i++){
       thefullImages[i] = new Image();
       thefullImages[i].src = value[i];
   }
  
} 

function gallery2getserver() {
     var value = document.URL;
     var text = value.split("/");
     return text[0]+'//'+text[2];
}     

function gallery2preload_finished() {
    var url = gallery2getserver()+'/wiki/modern/img/star_on.png';
    return url;
}

function gallery2add_comments() {
  var alias_text = document.slideform.alias.value;
  var exif_date_text = document.slideform.exif_date.value;
  var index = document.slideform.slide.selectedIndex;
  var alias = alias_text.split("!,!");
  var exif = exif_date_text.split(",");
  document.getElementById("gallery2_alias_text").innerHTML = alias[index];
  document.getElementById("gallery2_exif_date_text").innerHTML = exif[index];
}

function gallery2next_slide() {
   if (document.slideform.slide[current+1]) {
      document.images.show.src = theImages[current+1].src;
      document.slideform.slide.selectedIndex = ++current;
      gallery2add_comments();
   }
   else gallery2first_slide();
   document.getElementById("gallery2_first_slide").innerHTML = '<img src="'+gallery2getserver()+'/wiki/modern/img/first.png" onclick="gallery2first_slide();" name="fs"  title="first slide" >';
   document.getElementById("gallery2_last_slide").innerHTML = '<img src="'+gallery2getserver()+'/wiki/modern/img/last.png" onclick="gallery2last_slide();" name="fs"  title="last slide" >';
}
function gallery2previous_slide() {
   if (current-1 >= 0) {
      document.images.show.src = theImages[current-1].src;  
      document.slideform.slide.selectedIndex = --current;
      gallery2add_comments(); 
     
   }
   else gallery2last_slide();
   
   document.getElementById("gallery2_first_slide").innerHTML = '<img src="'+gallery2getserver()+'/wiki/modern/img/first.png" onclick="gallery2first_slide();" name="fs"  title="first slide" >';
   document.getElementById("gallery2_last_slide").innerHTML = '<img src="'+gallery2getserver()+'/wiki/modern/img/last.png" onclick="gallery2last_slide();" name="fs"  title="last slide" >';
}
function gallery2first_slide() {
   current = 0;
   document.images.show.src = theImages[0].src;  
   document.slideform.slide.selectedIndex = 0;
   gallery2add_comments();
   document.getElementById("gallery2_first_slide").innerHTML = '<img src="'+gallery2getserver()+'/wiki/modern/img/first_disabled.png" title="first slide" >';
   document.getElementById("gallery2_last_slide").innerHTML = '<img src="'+gallery2getserver()+'/wiki/modern/img/last.png" onclick="gallery2last_slide();" name="fs"  title="last slide" >';
}
function gallery2last_slide() {
   current = document.slideform.slide.length-1;
   document.images.show.src = theImages[current].src; 
   document.slideform.slide.selectedIndex = current;
   gallery2add_comments();
   document.getElementById("gallery2_first_slide").innerHTML = '<img src="'+gallery2getserver()+'/wiki/modern/img/first.png" onclick="gallery2first_slide();" name="fs"  title="first slide" >';
   document.getElementById("gallery2_last_slide").innerHTML = '<img src="'+gallery2getserver()+'/wiki/modern/img/last_disabled.png"  title="last slide" >';
}

function gallery2switch_images() {
   if (document.slideform.flag.value == "webnail") {
      var list = document.slideform.full_list.value;
      var name = document.slideform.full_name.value;
      document.slideform.flag.value = "fullscreen";
      theImages = thefullImages;
   } else {
     var list = document.slideform.webnail_list.value;
     var name = document.slideform.webnail_name.value;
     document.slideform.flag.value = "webnail";
     theImages = thewebImages;
   }

   var value = list.split(",");
   var alias = name.split(",");

   var n = value.length;

   for (i = 0; i <  n-1; i++){
      document.slideform.slide[i].value=value[i];
      document.slideform.slide[i].text=alias[i];
   }
   document.images.show.src = theImages[current].src; 
}

function gallery2ap(text) {
   document.slideform.slidebutton.value = (text == "Stop") ? "Start" : "Stop";
   gallery2rotate();
}

function gallery2change() {
   current = document.slideform.slide.selectedIndex;
   document.images.show.src = theImages[current].src; 
   gallery2add_comments(); 
   document.getElementById("gallery2_first_slide").innerHTML = '<img src="'+gallery2getserver()+'/wiki/modern/img/first.png" onclick="gallery2first_slide();" name="fs"  title="first slide" >';
   document.getElementById("gallery2_last_slide").innerHTML = '<img src="'+gallery2getserver()+'/wiki/modern/img/last.png" onclick="gallery2last_slide();" name="fs"  title="last slide" >';
}

function gallery2rotate() {
   if (document.slideform.slidebutton.value == "Stop") {
      current = (current == document.slideform.slide.length-1) ? 0 : current+1;
      document.images.show.src = theImages[current].src; 
      document.slideform.slide.selectedIndex = current;
      gallery2add_comments(); 
      document.getElementById("gallery2_first_slide").innerHTML = '<img src="'+gallery2getserver()+'/wiki/modern/img/first.png" onclick="gallery2first_slide();" name="fs"  title="first slide" >';
      document.getElementById("gallery2_last_slide").innerHTML = '<img src="'+gallery2getserver()+'/wiki/modern/img/last.png" onclick="gallery2last_slide();" name="fs"  title="last slide" >';
      rotate_delay = document.slideform.duration.value;
      window.setTimeout("gallery2rotate()", rotate_delay);
   }
}
//  End -->
</script> 
'''% { 
  'counter':counter} 

   return html  

def html_show_image(request,pagename,url_wiki_page,full,alias,exif_date,target,idx):
   
    option_webnail = option_list(AttachFile.getAttachUrl(pagename,target[idx],request),pagename,target,request)
    
    this_full_list = ''
    for s in full:
        this_full_list += AttachFile.getAttachUrl(pagename,s,request)+','
        
    this_webnail_list = ''    
    for s in target:
        this_webnail_list += AttachFile.getAttachUrl(pagename,s,request)+','
        
    html = '''
<left>
<form name=slideform method="POST">
   <input type="hidden" name="full_list" value='%(this_full_list)s'>
   <input type="hidden" name="full_name" value='%(this_full_name)s'>
   <input type="hidden" name="flag" value="webnail">
   <input type="hidden" name="webnail_list" value='%(this_webnail_list)s'>
   <input type="hidden" name="webnail_name" value='%(this_webnail_name)s'>
   <input type="hidden" name="alias" value='%(this_alias_list)s'>
   <input type="hidden" name="exif_date" value='%(this_exif_date_list)s'>
   <BR>
   <table><tr><td bgcolor="#C0C0C0"><strong>Slide: </strong></td>
   <td bgcolor="#C0C0C0">
      <select name="slide" onChange="gallery2change();" >
        %(option_webnails)s
      </select>
   </td>
   <td bgcolor="#C0C0C0">
   <input type="button" name="slidebutton" onClick="gallery2ap(this.value);" value="Start" title="AutoPlay">
   </td>
   <td bgcolor="#C0C0C0">
   <strong>Duration: </strong>
   </td>
   <td bgcolor="#C0C0C0">
   <input type="input" name="duration"  value="1000" size="5" title="Duration">
   </td>
   <td bgcolor="#C0C0C0" align="left" >  
   <P><SPAN id="gallery2_preloadstatus"></SPAN></P>  
   </td>

   </tr>
   </table>
   <BR>  
   <table align="center" cellspacing=1 cellpadding=4 bgcolor="#000000">
   <tr>
      <td align="center" bgcolor="white">
      </td>
   </tr>
   <tr>
      
      <td align="center" bgcolor="#C0C0C0">
         <SPAN id="gallery2_first_slide"><img src="%(server)s/wiki/modern/img/first.png" onclick="gallery2first_slide();" name="fs"  title="first slide" ></SPAN>
         <img src="%(server)s/wiki/modern/img/previous.png" onclick="gallery2previous_slide();"  title="previous slide" >
         <img src="%(server)s/wiki/modern/img/next.png" onClick="gallery2next_slide();"  title="next slide" >
         <SPAN id="gallery2_last_slide"><img src="%(server)s/wiki/modern/img/last.png" onClick="gallery2last_slide();"  title="last slide" ></SPAN>
         <input type="image" value="submit" src="%(server)s/wiki/modern/img/back.png" title="return to %(pagename)s">
      </td>
   </tr>
   <tr>
      <td align="center" bgcolor="white"">
         <img src="%(this_image)s" name="show" onClick="gallery2switch_images();">
      </td>
  </tr>
  <tr valign="center">
     <td bgcolor="#C0C0C0" align="left">
     <P><SPAN id="gallery2_alias_text">%(this_alias_text)s</SPAN></P>
     </td></tr>
   <tr valign="center">
     <td bgcolor="#C0C0C0" align="left">  
     <P><SPAN id="gallery2_exif_date_text">%(this_exif_date_text)s</SPAN></P>
     </td>
  </tr>
  <tr>
      <td align="center" bgcolor="white">
      </td>
   </tr>
  </table>
  <BR>  
  <table>
  <tr>
   <td bgcolor="#C0C0C0" align="left" >  
   <P><SPAN id="gallery2_status">%(comment)s</SPAN></P>  
   </td>
   </tr>
   </table>
</form>
</center>
''' % {
"server" : 'http://'+request.server_name+':' + str(request.server_port), 
"base_url" : request.getScriptname(),

"this_full_list" : this_full_list,
"this_full_name" : string.join(full,','),
"this_webnail_list" : this_webnail_list,
"this_webnail_name" : string.join(target,','),

"this_alias_text": to_htmltext(alias[idx]),
"this_alias_list" :  to_htmltext(string.join(alias,'!,!')),
"this_exif_date_text": exif_date[idx],
"this_exif_date_list" :string.join(exif_date,','),

"this_image" : AttachFile.getAttachUrl(pagename,target[idx],request),
"url_wiki_page" : url_wiki_page,
"comment" : "Click on the image for the next higher/lower resolution",
"pagename" : pagename,
"option_webnails" : option_webnail
}

    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
    
    if version.release < '1.5.0' :
       return result.strip()
    else:
       result = result.strip()
       result = result.replace('<a id="line-1"></a><p>','')  
       result = result.replace('</p>','') 
       return result


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,
                            body_onload = "gallery2preload();",
                            html_head = html_js(AttachFile.getAttachUrl(pagename,target,request),idx))
                  
        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
       
        
    elif request.form['do'][0] == 'PS' :
        msg = None
        
    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 version.release < '1.5.0' :
            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()
