#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright 2014 Murat Guven <muratg@online.de>
# This  due_date plugin provides a due date for tasks in due date
# format for ZimWiki from Jaap Karssenberg
# V0.2

import gtk
import gtk.gdk
import os.path
import os
import gobject

from zim.plugins import PluginClass, WindowExtension, extends
from zim.actions import action
from zim.config import config_file, XDG_CONFIG_HOME
import zim.datetimetz as datetime

import logging
logger = logging.getLogger('zim.plugins.duedate')


class DueDatePlugin(PluginClass):
	plugin_info = {
		'name': _('Due date'), # T: plugin name
		'description': _('''\
This plugin provides the date in due date format "[d:date]" for a task
attached to <ctrl>.

It looks for a due date format ( entry starting with [d:) )
within the dates.list file maintained by the date function <ctrl>D.
Standard is [d: %Y-%m-%d]

Value add is:
 - quicker access to due date
 - add x days to due date (see configuration)

(V0.2)
'''), # T: plugin description
		'author': "Murat Güven",
		'help': 'Plugins:Due date',
	}

	plugin_preferences = (
		# T: label for plugin preferences dialog
		('due_date_plus', 'int', _('Add days to today [d:today + days]'), 0, (0, 365)),
		# T: plugin preference
	)


@extends('MainWindow')
class MainWindowExtension(WindowExtension):

	uimanager_xml = '''
	<ui>
	<menubar name='menubar'>
		<menu action='tools_menu'>
			<placeholder name='plugin_items'>
				<menuitem action='due_date'/>
			</placeholder>
		</menu>
	</menubar>
	</ui>
	'''

	@action(_('Due_Date'), accelerator='<ctrl>period') # T: menu item

	def due_date(self):
		current_date = datetime.date.today()
		# get the user's due date format
		format = self.get_format()
		# get the current date + x dates according to the days given in prefs
		due_date = current_date + datetime.timedelta(days=self.plugin.preferences['due_date_plus'])
		# now put the due date into the format
		date_with_format = datetime.strftime(format, due_date)

		#add due date string into textbuffer at cursor
		buffer = self.window.pageview.view.get_buffer()
		cursor = buffer.get_iter_at_mark(buffer.get_insert())
		buffer.insert(cursor, date_with_format)

	def get_format(self):
		#get the dates.list config file
		file = config_file('dates.list')
		format = "[d: %Y-%m-%d]" # This is the given standard format
		# look for a due date format in dates.list file
		for line in file.readlines():
			line = line.strip()
			if not line.startswith("[d:"):
				continue
			if format in line:
				return format
			else:
				format = line
		return format

