## $Id: browser.py 7447 2012-01-10 21:38:44Z henrik $
##
## Copyright (C) 2011 Uli Fouquet & Henrik Bettermann
## 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
##
"""UI components for accesscodes.
"""
import grok
from datetime import datetime
from hurry.workflow.interfaces import InvalidTransitionError
from waeup.sirp.browser.resources import datatable
from waeup.sirp.browser import SIRPPage, SIRPAddFormPage
from waeup.sirp.browser.breadcrumbs import Breadcrumb
from waeup.sirp.browser.viewlets import (
    AdminTask, AddActionButton, SearchActionButton, BatchOpButton, ManageLink)
from waeup.sirp.interfaces import ISIRPObject

from waeup.sirp.accesscodes.interfaces import (
    IAccessCodeBatchContainer, IAccessCodeBatch,
    )
from waeup.sirp.accesscodes.catalog import search
from waeup.sirp.browser.layout import action

grok.context(ISIRPObject)

class BatchContainerPage(SIRPPage):
    grok.name('index')
    grok.context(IAccessCodeBatchContainer)
    grok.template('batchcontainer')
    grok.require('waeup.manageACBatches')

    title = 'Access Code Batches'
    pnav = 0

    def update(self, batches=None, archive=None, delete=None):
        if archive is None and delete is None:
            return
        if not batches:
            self.flash('No batch selected.')
            return
        if isinstance(batches, basestring):
            batches = [batches]
        for name in batches:
            batch = self.context[name]
            csv_file = batch.archive()
            self.flash('Archived %s (%s)' % (name, csv_file))
            if delete is None:
                continue
            del self.context[name]
            self.flash('Deleted batch %s' % name)

class AddBatchPage(SIRPAddFormPage):
    grok.name('add')
    grok.context(IAccessCodeBatchContainer)
    grok.require('waeup.manageACBatches')

    label = 'Create Access Code Batch'
    pnav = 0

    form_fields = grok.AutoFields(IAccessCodeBatch).select(
        'prefix', 'entry_num', 'cost')

    @action('Cancel')
    def cancel(self, *args, **kw):
        self.flash('Batch creation cancelled.')
        self.redirect(self.url(self.context))

    @action('Create batch')
    def createBatch(self, **data):
        creator = self.request.principal.id
        creation_date = datetime.now()
        data.update(creation_date=creation_date, creator=creator)
        batch = self.context.createBatch(**data)
        csv_file = batch.createCSVLogFile()
        self.context._p_changed = True
        self.flash('Batch created (%s entries)' % data['entry_num'])
        self.flash('Data written to %s' % csv_file)
        self.redirect(self.url(self.context))

class ReimportBatchPage(SIRPPage):
    """Screen for reimporting AC batches.
    """
    grok.name('reimport')
    grok.context(IAccessCodeBatchContainer)
    grok.template('reimportbatchpage')
    grok.require('waeup.manageACBatches')

    title = 'Reimport Access Code Batches'
    pnav = 0

    def update(self, filenames=None, reimport=None, cancel=None):
        if cancel is not None:
            self.flash('Reimport cancelled.')
            self.redirect(self.url(self.context))
            return
        if reimport is None:
            return
        if not filenames:
            self.flash('No file chosen. Action cancelled.')
            self.redirect(self.url(self.context))
            return
        if isinstance(filenames, basestring):
            filenames = [filenames]
        userid = self.request.principal.id
        for filename in filenames:
            try:
                self.context.reimport(filename, userid)
            except KeyError:
                self.flash('This batch already exists: %s' % filename)
                continue
            self.flash('Successfully reimported: %s' % filename)
        self.redirect(self.url(self.context))

class BatchContainerSearchPage(SIRPPage):
    grok.name('search')
    grok.context(IAccessCodeBatchContainer)
    grok.template('searchpage')
    grok.require('waeup.manageACBatches')

    title = 'Access Codes'
    pnav = 0
    label = 'Search and manage access codes'

    def update(self, *args, **kw):
        datatable.need()
        form = self.request.form
        self.hitlist = []
        if 'searchterm' in form and form['searchterm']:
            self.searchterm = form['searchterm']
            self.searchtype = form['searchtype']
        elif 'old_searchterm' in form:
            self.searchterm = form['old_searchterm']
            self.searchtype = form['old_searchtype']
        else:
            return
        #import pdb; pdb.set_trace()
        if not 'entries' in form:
            self.hitlist = search(query=self.searchterm,
                searchtype=self.searchtype, view=self)
            return
        entries = form['entries']
        if isinstance(entries, basestring):
            entries = [entries]
        for entry in entries:
            if 'disable' in form:
                try:
                    comment = u"AC disabled"
                    self.context.disable(entry, comment)
                    self.flash('%s disabled.' % entry)
                except InvalidTransitionError:
                    self.flash('%s: Disable transition not allowed.' % entry)
            elif 'enable' in form:
                try:
                    comment = u"AC re-enabled"
                    self.context.enable(entry, comment)
                    self.flash('%s (re-)enabled.' % entry)
                except InvalidTransitionError:
                    self.flash('%s: Re-enable transition not allowed.' % entry)
        self.hitlist = search(query=self.searchterm,
            searchtype=self.searchtype, view=self)
        return

class BatchContainerBreadcrumb(Breadcrumb):
    """A breadcrumb for ac batch containers.
    """
    grok.require('waeup.manageACBatches')
    grok.context(IAccessCodeBatchContainer)
    title = u'Access Code Batches'
    parent_viewname = 'administration'

class BatchContainerSearchBreadcrumb(Breadcrumb):
    """A breadcrumb for ac batch containers search page.
    """
    grok.require('waeup.manageACBatches')
    grok.context(IAccessCodeBatchContainer)
    grok.name('search')
    title = u'Search Access Codes'
    viewname = 'search'
    parent_viewname = 'index'

class AdminTaskManageACBatches(AdminTask):
    """Entry on administration page that links to batch container.
    """
    grok.order(5)
    grok.require('waeup.manageACBatches')
    grok.template('admintaskacbatches')

    link_title = 'Access Code Batches'
    target_viewname = 'accesscodes'

class CreateBatchButton(AddActionButton):
    """Action button on batch container page which links to batch creation.
    """
    grok.context(IAccessCodeBatchContainer)
    grok.view(BatchContainerPage)
    grok.require('waeup.manageACBatches')
    text = 'Add Access Code Batch'

class ReimportBatchButton(BatchOpButton):
    """Action button on batch container page which links to batch reimport.
    """
    grok.context(IAccessCodeBatchContainer)
    grok.view(BatchContainerPage)
    grok.require('waeup.manageACBatches')
    target = 'reimport'
    text = 'Reimport Access Code Batch'

class SearchAccessCodeButton(SearchActionButton):
    """Action button on batch container page which links to search.
    """
    grok.context(IAccessCodeBatchContainer)
    grok.view(BatchContainerPage)
    grok.require('waeup.manageACBatches')
    text = 'Search Access Codes'

class ManageAccessCodes(ManageLink):
    """Link in upper left box to access code management.
    """
    grok.order(6)
    grok.require('waeup.manageACBatches')

    link = u'accesscodes'
    text = u'Access Codes'
