# -*- coding: iso-8859-1 -*-
"""
    MoinMoin - ImageBrowserContent Macro
    Version 0.1

    An image browser with a content panel which avoids surge protection.
    
    [[ImageBrowserContent(index, file0, file1, ...)]]
    [[ImageBrowserContent(file0, file1, ...)]]
    [[ImageBrowserContent(index)]]
    [[ImageBrowserContent]]
    
    Where index is the 0 based index of the image to show by default, and
          file0, file1, ... are the images to display

    If omitted, index defaults to 0 (the first image) and file0, file1, ...
    defaults to all image attachments on the current page.

    Comment line 119 and uncomment 120 if you don't want to use the Thumbnail
    action (Javascript comment, not Python).

    @copyright: 2007 by Kenneth Bull
    @license: GNU GPL, see COPYING for details.

"""

def parseArgs(args):
    if args == None:
        return []
    params = [""]
    quote = ""
    i = 0
    while i < len(args):
        c = args[i]
        if quote == "":
            if ((c == '"') or (c == "'")) and (params[-1] == ""):
                quote = c
                params[-1] = ""
            elif c == ',':
                params.append("")
            elif (c != ' ') or (params[-1] != ""):
                params[-1] += c
        else:
            if c == quote:
                quote = ""
            else:
                params[-1] += c
        i += 1
    return params

def getImageList(request, pagename):
    from MoinMoin.action.AttachFile import _get_files, getFilename
    import os, mimetypes
    files = _get_files(request, pagename)
    imgs = []
    for f in files:
        if os.path.isfile(getFilename(request, pagename, f)) and (str(mimetypes.guess_type(f)[0])[:5] == "image"):
            imgs.append(f)
    return imgs

import StringIO
from MoinMoin.Page import Page
from MoinMoin import wikiutil

def getPageContent(request, formatter, pagename):
    _ = request.getText

    inc_name = wikiutil.AbsPageName(request, formatter.page.page_name, pagename)
    this_page = formatter.page

    if not hasattr(this_page, '_macroInclude_pagelist'):
        this_page._macroInclude_pagelist = {}

    if this_page._macroInclude_pagelist.has_key(inc_name):
        return '<p><strong class="error">Recursive include of "%s" forbidden</strong></p>' % inc_name

    fmt = formatter.__class__(request, is_included=True)
    fmt._base_depth = formatter._base_depth
    inc_page = Page(request, inc_name, formatter=fmt)

    # set or increment include marker
    this_page._macroInclude_pagelist[inc_name] = \
        this_page._macroInclude_pagelist.get(inc_name, 0) + 1

    inc_page._macroInclude_pagelist = this_page._macroInclude_pagelist

    if not hasattr(request, "_Include_backto"):
        request._Include_backto = this_page.page_name

    # output the included page
    strfile = StringIO.StringIO()
    request.redirect(strfile)
    try:
        cid = request.makeUniqueID("Include_%s" % wikiutil.quoteWikinameURL(inc_page.page_name))
        inc_page.send_page(request, content_only=1, content_id=cid,
                           omit_footnotes=True)
    finally:
        request.redirect()

    # decrement or remove include marker
    if this_page._macroInclude_pagelist[inc_name] > 1:
        this_page._macroInclude_pagelist[inc_name] = \
            this_page._macroInclude_pagelist[inc_name] - 1
    else:
        del this_page._macroInclude_pagelist[inc_name]

    # return include text
    return strfile.getvalue()

imgbrswrscript = """
<script type="text/javascript">
	function imgbrwsr_content_update()  {

		link = document.getElementById(this.element.id+"_link");
		link.href = this.images[this.index][0]+"?action=AttachFile&do=get&target="+this.images[this.index][1];
		link.title = this.images[this.index][2];

		img = document.getElementById(this.element.id+"_image");
		img.src = this.images[this.index][0]+"?action=Thumbnail&w=320&h=240&target="+this.images[this.index][1];
//		img.src = this.images[this.index][0]+"?action=AttachFile&do=get&target="+this.images[this.index][1];
		img.alt = this.images[this.index][2];

		for (i = 0; i < this.images.length; ++i)  {
			document.getElementById(this.element.id+"_text_"+i).style.display = (i == this.index)? "block": "none";
		}

		document.getElementById(this.element.id+"_edit").href = this.images[this.index][0]+"/"+this.images[this.index][1]+"?action=edit"
		document.getElementById(this.element.id+"_view").href = this.images[this.index][0]+"/"+this.images[this.index][1]+"?action=show"
		
		if (this.index == 0)	{
			document.getElementById(this.element.id+"_frst").style.display = "none";
			document.getElementById(this.element.id+"_back").style.display = "none";
		} else {
			document.getElementById(this.element.id+"_frst").style.display = "block";
			document.getElementById(this.element.id+"_back").style.display = "block";
		}
		if (this.index == this.images.length - 1)	{
			document.getElementById(this.element.id+"_next").style.display = "none";
			document.getElementById(this.element.id+"_last").style.display = "none";
		} else {
			document.getElementById(this.element.id+"_next").style.display = "block";
			document.getElementById(this.element.id+"_last").style.display = "block";
		}
	}
	function imgbrwsr_content_goto(imgno)	{
		while (imgno < 0)
			imgno += this.images.length;
		if (imgno >= this.images.length)
			imgno %%= this.images.length;
		this.index = imgno;
		this.update();
	}
	function imgbrwsr_content_offset(off)	{
		this.go(this.index+off);
	}
	function imgbrwsr_content_expand()   {
		expand = document.getElementById(this.element.id+"_expand");
		expandimg = document.getElementById(this.element.id+"_expand_img");
		textdiv = document.getElementById(this.element.id+"_text");
		buttondiv = document.getElementById(this.element.id+"_text_buttons");
		if (textdiv.style.display == 'none')    {
			this.element.style.width = '695px';
			this.element.style.background = 'url(%(frameexpandedimg)s)';
			textdiv.style.display = 'block';
			buttondiv.style.display = 'block';
			expand.title = 'Hide the content panel';
			expandimg.src = '%(closeimg)s';
                } else  {
			buttondiv.style.display = 'none';
			textdiv.style.display = 'none';
			this.element.style.background = 'url(%(frameimg)s)';
			this.element.style.width = '358px';
			expand.title = 'Show the content panel';
			expandimg.src = '%(openimg)s';
		}
	}
	var imgbrwsr_contents = new Array();
	function imgbrwsr_content(element, ndx, imgs)   {
		this.id     = imgbrwsr_contents.length;
		this.element= element;
		this.index  = ndx;
		this.images = imgs;
		this.go     = imgbrwsr_content_goto;
		this.offset = imgbrwsr_content_offset;
		this.update = imgbrwsr_content_update;
		this.expand = imgbrwsr_content_expand;
		imgbrwsr_contents[this.id] = this;
		document.getElementById(this.element.id+"_frst").href = "javascript:imgbrwsr_contents["+this.id+"].go(0);";
		document.getElementById(this.element.id+"_back").href = "javascript:imgbrwsr_contents["+this.id+"].offset(-1);";
		document.getElementById(this.element.id+"_next").href = "javascript:imgbrwsr_contents["+this.id+"].offset(1);";
		document.getElementById(this.element.id+"_last").href = "javascript:imgbrwsr_contents["+this.id+"].go(-1);";
		document.getElementById(this.element.id+"_expand").href = "javascript:imgbrwsr_contents["+this.id+"].expand();";
	}
</script>
"""

def execute(macro, args):
    from MoinMoin.action import AttachFile
    request = macro.request;

    try:
        macro.formatter._imgbrwsr_content_id
        output = ""
    except:
        output = imgbrswrscript % {'frameimg':          request.theme.img_url('imgbrwsr/frame.png'),
                                   'frameexpandedimg':  request.theme.img_url('imgbrwsr/frame_expanded_buttons.png'),
                                   'closeimg':          request.theme.img_url('imgbrwsr/close.png'),
                                   'openimg':           request.theme.img_url('imgbrwsr/open.png')}
        macro.formatter._imgbrwsr_content_id = 0

    p = parseArgs(args)
    try:
        ndx = int(p[0])
        p.pop(0)
    except:
        ndx = 0

    if len(p) == 0:
        p = getImageList(macro.request, macro.formatter.page.page_name)

    i = 0
    script = "<script type='text/javascript'>\n\t(new imgbrwsr_content(document.getElementById('imgbrwsr_content%d'), %d, new Array(" % (macro.formatter._imgbrwsr_content_id, ndx)
    output += """<div id='imgbrwsr_content%(id)d' style='float:left; width:358px; height:312px; position:relative; background:url(%(frameimg)s);'>
    <a id='imgbrwsr_content%(id)d_link' style='position:absolute; left:19px; top:20px; display:block;'><img id='imgbrwsr_content%(id)d_image' style="width:320px; height:240px; border:none;" /></a>
    <div id='imgbrwsr_content%(id)d_text' style='position:absolute; left:354px; top:19px; width:320px; height:240px; overflow:auto; display:none;'>""" % {'id': macro.formatter._imgbrwsr_content_id,
                                                                                                                                                          'frameimg': request.theme.img_url('imgbrwsr/frame.png')}
    for f in p:
        pagename, filename = AttachFile.absoluteName(f, macro.formatter.page.page_name)
        if i > 0:
            script += ", "
        script += "new Array('%s', '%s', '%s')" % (pagename, filename, f)
        output += "<div id='imgbrwsr_content%(id)d_text_%(i)d' style='display:none;'>%(text)s</div>" % {'id': macro.formatter._imgbrwsr_content_id, 'i': i, 'text': getPageContent(macro.request, macro.formatter, pagename+'/'+filename)}
        i += 1
    script += "))).update();\n</script>"
    output += """</div>
    <a id='imgbrwsr_content%(id)d_frst' title='Go to the first image'    style='position:absolute; left: 11px; top:266px;'><img src='%(firstimg)s' style='border:none;' alt='first' /></a>
    <a id='imgbrwsr_content%(id)d_back' title='Go to the previous image' style='position:absolute; left: 55px; top:266px;'><img src='%(backimg)s'  style='border:none;' alt='back'  /></a>
    <a id='imgbrwsr_content%(id)d_next' title='Go to the next image'     style='position:absolute; left:271px; top:266px;'><img src='%(nextimg)s' style='border:none;'  alt='next'  /></a>
    <a id='imgbrwsr_content%(id)d_last' title='Go to the last image'     style='position:absolute; left:303px; top:266px;'><img src='%(lastimg)s' style='border:none;'  alt='last'  /></a>
    <a id='imgbrwsr_content%(id)d_expand' title='Show the content panel' style='position:absolute; left:343px; top:129px;'><img id='imgbrwsr_content%(id)d_expand_img' src="%(openimg)s" style='border:none;' /></a>
    <div id='imgbrwsr_content%(id)d_text_buttons' style='display:none;'>
        <a id='imgbrwsr_content%(id)d_edit' title='Edit text' style='position:absolute; left:344px; top:270px; display:block;' onmouseover='document.getElementById("imgbrwsr_content%(id)d_view").style.display="none";' onmouseout='document.getElementById("imgbrwsr_content%(id)d_view").style.display="block";'><img src='%(editimg)s' style='border:none;' alt='edit' /></a>
        <a id='imgbrwsr_content%(id)d_view' title='View text' style='position:absolute; left:370px; top:270px; display:block;' onmouseover='document.getElementById("imgbrwsr_content%(id)d_edit").style.display="none";' onmouseout='document.getElementById("imgbrwsr_content%(id)d_edit").style.display="block";'><img src='%(viewimg)s' style='border:none;' alt='view' /></a>
    </div>
</div>""" % {'id':          macro.formatter._imgbrwsr_content_id,
             'firstimg':    request.theme.img_url('imgbrwsr/first.png'),
             'backimg':     request.theme.img_url('imgbrwsr/back.png'),
             'nextimg':     request.theme.img_url('imgbrwsr/next.png'),
             'lastimg':     request.theme.img_url('imgbrwsr/last.png'),
             'openimg':     request.theme.img_url('imgbrwsr/open.png'),
             'editimg':     request.theme.img_url('imgbrwsr/edit.png'),
             'viewimg':     request.theme.img_url('imgbrwsr/view.png')}
    macro.formatter._imgbrwsr_content_id += 1
    return macro.formatter.rawHTML(output+script)
