#-*- coding: utf-8 -*-
""" 
Sorter to sort one level of input
===================================

This parser is adapted from SortText and used to sort text lines which are delimited by a special symbol.  The
sort direction and the column to sort can be specified. For the sort column the type can be specified as "text"
or "date". The delimiters are omitted in the final output.

Defaults are
delimiter=''
column='1'
column_type='text'
sort_direction='up'

delimiter is the empty string so that a normal text search is done by default.

Install
-------
Put it in your wiki/data/plugin/parser/


Example
-------

{{{
#!Sorter column=2,column_type=date,sort_dir=up,date_format=%d.%m.%Y
* | B | 1.1.2005
* | A | 1.2.2006
* | D | 4.1.2005
* | C | 5.4.2000 
}}}

Result::
* C 5.4.2000 
* B 1.1.2005 
* D 4.1.2005 
* A 1.2.2006


Legal
-----
@copyright  2005 WilliRichert <w.richert@gmx.net>
@copyright  2005 ReimarBauer <R.Bauer@fz-juelich.de>


This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
"""



Dependencies = []
import string, time
from MoinMoin.parser import wiki
from MoinMoin import wikiutil

class Parser:

	def __init__(self, raw, request, **kw):
		self.raw = raw
		self.request = request
		self.form = request.form
		self._ = request.getText
		
		self.kw = {
			'delimiter': '',
			'column': '1',
			'column_type': 'text',
			'date_format':'%Y-%m-%d',
			'sort_dir': 'up'
		}


		for arg in kw.get('format_args','').split(','):
			if arg.find('=') > -1:
				key, value=arg.split('=')
				self.kw[key]=wikiutil.escape(value, quote=1)

	
	def format(self, formatter):
	
		Dict = {}
		raw = self.raw.split('\n')
		
		delim = self.kw['delimiter']
		data = []
		for line in raw:
			data.append(line.split(delim))
		
		up = self.kw['sort_dir']=='up'
		def _cmp(a, b):
			if self.kw['column_type']=="date":
				col, df = int(self.kw['column']), self.kw['date_format']
				a = time.strptime(a[col].strip(), df)
				b = time.strptime(b[col].strip(), df)
			
			if not up:
				a,b=b,a
			
			return cmp(a, b)
		
		data.sort(_cmp)
			
		raw = []
		for line in data:
			raw.append("".join(line))
			
		wikiizer = wiki.Parser(string.join(raw,"\n"),self.request) 
		wikiizer.format(formatter)


	
	
	
	
