# -*- coding: UTF-8 -*-

# Copyright (c) 2007 Daniele Favara <nomed@dsslive.org>.
#
# This 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, or (at your option) any
# later version.
#
# This software 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 software; see the file COPYING.  If not, write to the Free
# Software Foundation, Inc., 51 Franilin St, Fifth Floor, Boston, MA


from turbogears import expose, flash
from tginvoice.controllers import ControllerObj
from tginvoice.model import tables, database
from tginvoice.utils import form
from genshi.template import TemplateLoader
from genshi import XML, escape
from tginvoice import trml2pdf
from formencode import Invalid
from turbogears import identity, redirect, url
from cherrypy import request, response, session
import logging
log = logging.getLogger("tginvoice.controllers.project")
from plotkit import EasyPlot

class Projects(ControllerObj):

    @identity.require(identity.not_anonymous())
    @expose(template="tginvoice.templates.projects")
    def index(self, *args, **kw):
        #print "\n"*10, self.calendar , "\n"*10
        return dict(this=self)

    @identity.require(identity.not_anonymous())
    @expose(template="tginvoice.templates.projects_show")
    def show(self, id=None, format=None, *args, **kw):
        project = self._get_project(id)

        if not self.check_identity_user(project):
            return None
        data = self._get_tasks(project)
        ep = self._get_tasks_plot(data)
        data_active = self._get_tasks_active(project)
        ep_active = self._get_tasks_active_plot(data_active)
        ep_dummy = None
        if ep:
            ep_dummy = ep[ep.keys()[0]]
        #from toscawidgets.widgets.tinymce import TinyMCE

        #tiny = TinyMCE(id='tinymce')
        return dict(this=self,
                    project=project,
                    biller = self.pbiller,
                    customer = project.customer,
                    milestones = project.milestones,
                    csession = session,
                    data = data,
                    data_active = data_active,
                    ep = ep,
                    ep_active = ep_active,
                    #tiny = tiny,
                    ep_dummy = ep_dummy)

    @identity.require(identity.not_anonymous())
    @expose(template="tginvoice.templates.milestones_show")
    def show_milestone(self, id=None, *args, **kw):
        milestone = self._get_milestone(id)

        if not self.check_identity_user(milestone.project):
            return None
        data = self._get_tasks(milestone.project)
        ep = self._get_tasks_plot(data)
        data_active = self._get_tasks_active(milestone.project)
        ep_active = self._get_tasks_active_plot(data_active)
        ep_dummy = None
        if ep:
            ep_dummy = ep[ep.keys()[0]]
        #from toscawidgets.widgets.tinymce import TinyMCE

        #tiny = TinyMCE(id='tinymce')
        return dict(this=self,
                    milestone = milestone,
                    #data = data,
                    #data_active = data_active,
                    #ep = ep,
                    #ep_active = ep_active,
                    #tiny = tiny,
                    #ep_dummy = ep_dummy
                    )

    @identity.require(identity.not_anonymous())
    @expose()
    def del_task(self, id=None, *args, **kw):
        if kw.has_key('del_task'):
            pid = int(kw['del_task'])
            if session.get('tasks'):
                if len(session['tasks']) >= pid:
                    session['tasks'].pop(pid)
        raise redirect(url('new'))

    @identity.require(identity.not_anonymous())
    @expose()
    def set_needed(self, id=None, *args, **kw):
        if kw.has_key('select'):
            if kw['select'].has_key('customer'):
                if kw['select']['customer']:
                    session['customer'] = self._get_customer(kw['select']['customer'])
            if kw['select'].has_key('currency'):
                session['currency'] = kw['select']['currency']
        raise redirect(url('new'))



    @identity.require(identity.not_anonymous())
    @expose(template="tginvoice.templates.projects_new_task")
    def new_task(self, id=None, *args, **kw):
        project=self._get_project(id)

        if not self.check_identity_user(project):
            return None

        errors={}
        if kw.has_key('errors'):
            errors = kw['errors']
        new_task = {}
        if kw.has_key('new_task'):
            new_task = kw['new_task']
        for col in self.iterator_task_form + ['milestone_id']:
            if not new_task.has_key(col):
                new_task[col] = ''
        milestone = self._get_milestone(new_task['milestone_id'])
        if kw.has_key('actions'):
            if kw['actions'].has_key('save_task'):
                validate = form.Task()
                try:
                    new_task= validate.to_python(new_task)
                    tables.session.begin()
                    task_obj = tables.Task(**new_task)
                    milestone.tasks.append(task_obj)
                    tables.session.save(task_obj)
                    tables.session.commit()
                    raise redirect(url('.'))
                except Invalid, e:
                    errors = e.unpack_errors()
        return dict(this=self, project=project,
                    milestone = milestone,
                    errors = errors,
                    new_task = new_task,
                    calendar_enddate = self.calendar(id='enddate'),
                    calendar_begindate = self.calendar(id='begindate'),)

    @identity.require(identity.not_anonymous())
    @expose(template="tginvoice.templates.projects_new_milestone")
    def new_milestone(self, id=None, *args, **kw):
        project=self._get_project(id)

        if not self.check_identity_user(project):
            return None

        errors={}
        if kw.has_key('errors'):
            errors = kw['errors']
        new_milestone = {}
        if kw.has_key('new_milestone'):
            new_milestone = kw['new_milestone']
        for col in self.iterator_milestone_form:
            if not new_milestone.has_key(col):
                new_milestone[col] = ''
            if col == 'name':
                new_milestone['name'] = new_milestone['name'].lower()
            if col in ['begindate','enddate']:
                if kw.has_key(col):
                    new_milestone[col] = self.date_validate(kw[col])
        if kw.has_key('actions'):
            if kw['actions'].has_key('save_milestone'):
                validate = form.Milestone()
                try:
                    new_milestone = validate.to_python(new_milestone)
                    tables.session.begin()
                    milestone_obj = tables.Milestone()
                    for key, value in new_milestone.iteritems():
                        setattr(milestone_obj, key , value)
                    project.milestones.append(milestone_obj)
                    tables.session.save(milestone_obj)
                    tables.session.commit()
                    #tables.session.close()
                    raise redirect(url('.'))
                except Invalid, e:
                    errors = e.unpack_errors()

        return dict(this=self, project=project,
                    errors = errors,
                    new_milestone = new_milestone,
                    calendar_enddate = self.calendar(id='enddate'),
                    calendar_begindate = self.calendar(id='begindate'),)

    @identity.require(identity.not_anonymous())
    @expose(template="tginvoice.templates.projects_new")
    def new(self, *args, **kw):
        errors = {}
        if kw.has_key('errors'):
            errors = kw['errors']
        new_project = {}
        if kw.has_key('new_project'):
            new_project = kw['new_project']
        # add here session new_task as save
        for col in self.iterator_project_form + ['customer_id']:
            if not new_project.has_key(col):
                new_project[col] = ''
            if col == 'name':
                new_project['name'] = new_project['name'].lower()
            if col in ['begindate','enddate']:
                if kw.has_key(col):
                    new_project[col] = self.date_validate(kw[col])

        customer = self._get_customer(new_project['customer_id'])
        new_project['user_id'] = identity.current.user.user_id
        if new_project['name']:
            if database.get_project_unique(
                                    new_project['name'],
                                    new_project['user_id'],
                                    new_project['customer_id']
                                           ):
                errors['name'] = self.mapper_error['project_name_not_unique']
                kw['actions'] = {}
        if kw.has_key('actions'):
            if kw['actions'].has_key('save_project'):
                validate = form.Project()
                try:
                    new_project = validate.to_python(new_project)
                    tables.session.begin()
                    project_obj = tables.Project(**new_project)
                    tables.session.save(project_obj)
                    tables.session.commit()
                    raise redirect(url('.'))
                except Invalid, e:
                    errors = e.unpack_errors()

        return dict(this=self, projects=self.pprojects,
                    errors = errors,
                    new_project = new_project,
                    customer = customer,
                    calendar_enddate = self.calendar(id='enddate'),
                    calendar_begindate = self.calendar(id='begindate'),
                    )

