# -*- 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_
      
       Version 1.5.4-13  2006-08-02 based on 1.3.5-10                    
       FlorianFesti: changed some calls to more readable code                           
       ReimarBauer:  PEP 8
                     fixed of selecting an index of a scalar value
                     switch of release number to MoinMoin Version 1.5
                     duplicated call of html tag body and head removed
                     optional static path
                     table style changed
                     
       2006-08-11 1.5.4-14 RB bug fixed webf and thumbf changed to tmp. prefix always                

       2006-08-11 1.6.0-15 RB ported to 1.6.0 alpha version 

"""
Dependencies = []
import os, Image, StringIO, string, sys
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 text_moin_wiki
from MoinMoin.util import filesys

def get_path_url(request, pagename, attachment_path):
    url_prefix = request.cfg.url_prefix
    url_prefix = url_prefix.replace('/','')
    
    if hasattr(request.cfg, 'document_root'):

        static_path = "%(dir)s/tmp/Gallery2%(wiki_name)s/%(pagename)s" % {
              "wiki_name": request.getScriptname(),
              "pagename": pagename,
              "dir": request.cfg.document_root,
              }
        static_url = "%(prefix)s/tmp/Gallery2%(wiki_name)s/%(pagename)s/" % {
              "prefix": url_prefix,
              "wiki_name": request.getScriptname(),
              "pagename": pagename,
              }
    else:
        static_path = attachment_path
        static_url = AttachFile.getAttachUrl(pagename, '', request)

    static_url = string.replace(static_url,'//','/')  
    
    return static_path, static_url

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": this_image,
                "alias": s.replace('tmp.','')}
        else:
            txt += '<option value="%(name)s">%(alias)s' % {
                "name": this_image,
                "alias": s.replace('tmp.','')}

    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/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/img/first.png" onclick="gallery2first_slide();" name="fs"  title="first slide" >';
   document.getElementById("gallery2_last_slide").innerHTML = '<img src="'+gallery2getserver()+'/wiki/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/img/first.png" onclick="gallery2first_slide();" name="fs"  title="first slide" >';
   document.getElementById("gallery2_last_slide").innerHTML = '<img src="'+gallery2getserver()+'/wiki/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/img/first_disabled.png" title="first slide" >';
   document.getElementById("gallery2_last_slide").innerHTML = '<img src="'+gallery2getserver()+'/wiki/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/img/first.png" onclick="gallery2first_slide();" name="fs"  title="first slide" >';
   document.getElementById("gallery2_last_slide").innerHTML = '<img src="'+gallery2getserver()+'/wiki/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++){
      var al = alias[i];
      var al = al.replace("tmp.","");
      document.slideform.slide[i].value=value[i];
      document.slideform.slide[i].text=al;
   }
   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/img/first.png" onclick="gallery2first_slide();" name="fs"  title="first slide" >';
   document.getElementById("gallery2_last_slide").innerHTML = '<img src="'+gallery2getserver()+'/wiki/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/img/first.png" onclick="gallery2first_slide();" name="fs"  title="first slide" >';
      document.getElementById("gallery2_last_slide").innerHTML = '<img src="'+gallery2getserver()+'/wiki/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):
    attachment_path = AttachFile.getAttachDir(request, pagename)
    static_path, static_url = get_path_url(request, pagename, attachment_path )

    option_webnail = option_list(static_url + target[idx], pagename, target, request)
    static_path, static_url = get_path_url(request, pagename, attachment_path)
    
    inner_table_style = ' style="border-style:none; margin:10px;"'
    
    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 += static_url + s + ','

            
    html = '''
<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%(tablestyle)s>
    <tr>
     <td style="border-style:none" bgcolor="#C0C0C0"><strong>Slide: </strong></td>
     <td style="border-style:none" bgcolor="#C0C0C0">
       <select name="slide" onChange="gallery2change();" >
         %(option_webnails)s
       </select>
     </td>
     <td style="border-style:none" bgcolor="#C0C0C0">
      <input type="button" name="slidebutton" onClick="gallery2ap(this.value);" value="Start" title="AutoPlay">
     </td>
     <td style="border-style:none" bgcolor="#C0C0C0">
      <strong>Duration: </strong>
     </td>
     <td style="border-style:none" bgcolor="#C0C0C0">
      <input type="input" name="duration"  value="1000" size="5" title="Duration">
     </td>
   </tr>
   <tr>
     <td style="border-style:none" colspan="5" align="center" bgcolor="#C0C0C0">
     <SPAN id="gallery2_first_slide"><img src="%(server)s/wiki/img/first.png" onclick="gallery2first_slide();" name="fs"  title="first slide" ></SPAN>
     <img src="%(server)s/wiki/img/previous.png" onclick="gallery2previous_slide();"  title="previous slide" >
     <img src="%(server)s/wiki/img/next.png" onClick="gallery2next_slide();"  title="next slide" >
     <SPAN id="gallery2_last_slide"><img src="%(server)s/wiki/img/last.png" onClick="gallery2last_slide();"  title="last slide" ></SPAN>
     <input type="image" value="submit" src="%(server)s/wiki/img/back.png" title="return to %(pagename)s">
     </td>
   </tr>
   <tr>
    <td style="border-style:none" colspan="5" align="center" bgcolor="#C0C0C0">
     <img src="%(server)s/%(this_image)s" name="show" onClick="gallery2switch_images();">
    </td>
   </tr>
   <tr valign="center">
    <td style="border-style:none"colspan="5" bgcolor="#C0C0C0" align="left">
     <P><SPAN id="gallery2_alias_text">%(this_alias_text)s</SPAN></P>
    </td></tr>
   <tr valign="center">
    <td style="border-style:none" colspan="5" bgcolor="#C0C0C0" align="left">  
     <P><SPAN id="gallery2_exif_date_text">%(this_exif_date_text)s</SPAN></P>
    </td>
  </tr>
  <tr>
   <td style="border-style:none" colspan="5" bgcolor="#C0C0C0" align="left" >  
    <P><SPAN id="gallery2_status">%(comment)s</SPAN></P> 
   </td>
  
  </tr>
</table>
</form>
''' % {
"server": request.getQualifiedURL(),
"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_target": full[idx],

"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": static_url + target[idx], # 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,
"tablestyle": inner_table_style,
"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)
    command = request.form.get('do', ['none'])[0]

    if command == 'VS':
        web = {}
        images = request.form.get('target', [''])[0]
        images = images.split(',')
        target = images[0]
        images = (images[1:])

        full_image = request.form.get('full', [''])[0]
        full_image = full_image.split(',')
        full_target = full_image[0]
        full_image = (full_image[1:])

        all_description = request.form.get('alias', [''])[0]
        all_description = all_description.split('!,!')
        this_description = all_description[0]
        all_description = (all_description[1:])

        all_exif_date = request.form.get('exif_date', [''])[0]
        all_exif_date = all_exif_date.split(',')
        this_exif_date = all_exif_date[0]
        all_exif_date = (all_exif_date[1:])

        # XXX Check that all lists have same length

        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)

        static_path, static_url = get_path_url(request, pagename, attachment_path )

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

        image_link = request.formatter.image(**web)

        request.http_headers()

        request.setContentLanguage(request.lang)

        request.theme.send_title(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())
        request.theme.send_footer(pagename)
        msg = None

    elif command == 'PS':
        msg = None

    elif command == '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.get('target', [''])[0]
        file, ext = os.path.splitext(target)

        if ext == '.gif'  or  ext == '.png':
            img_type = 'PNG'
            thumbfile = "tmp.thumbnail_%(file)s.png" % {"file": file}
            webnail = "tmp.webnail_%(file)s.png" % {"file": file}
        else:
            img_type = "JPEG"
            thumbfile = "tmp.thumbnail_%(file)s.jpg"  % {"file": file}
            webnail = "tmp.webnail_%(file)s.jpg"  % {"file": file}

        static_path, static_url = get_path_url(request, pagename, attachment_path )

        thumb = os.path.join(static_path, thumbfile)
        webf = os.path.join(static_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 command == 'RM':
            if os.path.exists(infile + '.bak'):
               os.unlink("%(file)s.bak" % {"file": infile})
            filesys.rename(infile, "%(file)s.bak" % {"file": infile})
            msg = _('%(target)s deleted, backup in place' % {
                  'target':target})

        elif command == 'RL':
            im = Image.open(infile)
            os.remove(infile)
            im.rotate(90).save(infile, img_type)
            nim = Image.open(infile)
            nim.thumbnail((640, 640), Image.ANTIALIAS)
            os.remove(webf)
            nim.save(webf, img_type)
            nim.thumbnail((128, 128), Image.ANTIALIAS)
            os.remove(thumb)
            nim.save(thumb, img_type)
            msg = _('%(target)s rotated to left 90 degrees' % {
                  'target':target})

        elif command == 'RR':
            im = Image.open(infile)
            os.remove(infile)
            im.rotate(270).save(infile, img_type)

            nim = Image.open(infile)
            nim.thumbnail((640, 640), Image.ANTIALIAS)
            os.remove(webf)
            nim.save(webf, img_type)
            nim.thumbnail((128, 128), Image.ANTIALIAS)
            os.remove(thumb)
            nim.save(thumb, img_type)
            msg = _('%(target)s rotated to right 90 degrees' % {
                  'target':target})
        else:
            msg = _('action not implemented: %s') % (command, )
    else:
        msg = _('Your are not allowed to change images on this page: %s') % (pagename,)

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

    return()
