# -*- 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.       
        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-150
                              
                       

"""
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 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 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 exchanged for usage with Gallery2 -->


<!-- Begin
var rotate_delay = 1000; // delay in milliseconds (5000 = 5 secs)
current = %(counter)s;


theImages = new Array();
thewebImages =  new Array();
thefullImages =  new Array();

function preload() {
   
   list=document.slideform.webnail_list.value;
   
   value = list.split(","); 
   n=value.length;
   
   for (i = 0; i <  n-1; i++){
       theImages[i] = new Image();
       theImages[i].src = value[i];
   }   
   thewebImages = theImages;
   
   list=document.slideform.full_list.value;
   
   value = list.split(","); 
   n=value.length;
   
   for (i = 0; i <  n-1; i++){
       thefullImages[i] = new Image();
       thefullImages[i].src = value[i];
   }  
   
} 
   
 
function add_comments() {
  alias_text = document.slideform.alias.value;
  exif_date_text = document.slideform.exif_date.value;
  index = document.slideform.slide.selectedIndex;
  alias = alias_text.split("!,!");
  exif = exif_date_text.split(",");
  document.slideform.alias_text.value = alias[index] ;
  document.slideform.exif_date_text.value = exif[index];
}

function next_slide() {
   if (document.slideform.slide[current+1]) {
      document.images.show.src = theImages[current+1].src;
      document.slideform.slide.selectedIndex = ++current;
      add_comments();
   }
   else first_slide();
}
function previous_slide() {
   if (current-1 >= 0) {
      document.images.show.src = theImages[current-1].src;  
      document.slideform.slide.selectedIndex = --current;
      add_comments(); 
   }
   else last_slide();
}
function first_slide() {
   current = 0;
   document.images.show.src = theImages[0].src;  
   document.slideform.slide.selectedIndex = 0;
   add_comments();
}
function last_slide() {
   current = document.slideform.slide.length-1;
   document.images.show.src = theImages[current].src; 
   document.slideform.slide.selectedIndex = current;
   add_comments();
}

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

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

   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 ap(text) {
   document.slideform.slidebutton.value = (text == "Stop") ? "Start" : "Stop";
   rotate();
}

function change() {
   current = document.slideform.slide.selectedIndex;
   document.images.show.src = theImages[current].src ; 
   add_comments(); 
}

function rotate() {
   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;
      add_comments(); 
      rotate_delay = document.slideform.duration.value;
      window.setTimeout("rotate()", rotate_delay);
   }
}

//  End -->
</script>    '''% { 
  'this_image':this_image,
  '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 = '''
<body  onLoad="preload()">   
<center>
<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">

   <table cellspacing=1 cellpadding=4 bgcolor="#000000">
   <tr>
      <td align=center bgcolor="white">
      </td>
   </tr>
   <tr>
      <td align=center bgcolor="#C0C0C0">
         <img src="%(server)s/wiki/modern/img/first.png" onclick="first_slide();" name="fs"  title="first slide" >
         <img src="%(server)s/wiki/modern/img/previous.png" onclick="previous_slide();"  title="previous slide" >
         
         <input type="input" name="duration"  value="1000" size="5" title="Duration">
         <input type="button" name="slidebutton" onClick="ap(this.value);" value="Start" title="AutoPlay">
         
         <img src="%(server)s/wiki/modern/img/next.png" onClick="next_slide();"  title="next slide" >
         <img src="%(server)s/wiki/modern/img/last.png" onClick="last_slide();"  title="last slide" >
         <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="switch_images();">
      </td>
  </tr>
  <tr>
     <td align=center bgcolor="#C0C0C0">
        <select name="slide" onChange="change();" >
        %(option_webnails)s
        </select>
     </td>
  </tr>      
  <tr>
     <td bgcolor="#C0C0C0">
           <input type="button" name="alias_text"  value="%(this_alias_text)s">
     </td>
  </tr>
  <tr>
     <td bgcolor="#C0C0C0">
          <input type="button" name="exif_date_text"  value="%(this_exif_date_text)s">
     </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": alias[idx],
"this_alias_list" :  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,
"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
    
    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(html_js(AttachFile.getAttachUrl(pagename,target[idx],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 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()
