from zope.i18n import translate
from DateTime import DateTime
from Acquisition import aq_parent
from Products.CMFPlone import PloneMessageFactory as _pl

from Products.plonehrm.browser.base_edit import BaseEditView
from Products.plonehrm import PloneHrmMessageFactory as _p

from plonehrm.absence import AbsenceMessageFactory as _
from plonehrm.absence.content.file import AbsenceFile
from plonehrm.absence.content.file import schema
from plonehrm.absence.content.file import AbsenceFileSchema

class FileEditView(BaseEditView):
    """ Special view to edit absence files.
    """
    def translate_field_name(self, name):
        """ Returns the label of a field.
        """
        for field in AbsenceFileSchema.fields():
            if field.getName() == name:
                if field in self.schema.fields():
                    return translate(field.widget.label,
                                     target_language=self.lang())
                else:
                    return translate(_pl('label_' + name),
                                     target_language=self.lang(),
                                     context=self.request)
                    

    def get_form_fields(self):
        """ Provides the list of fields that should be present in
        the form
        """
        fields = ['title', 'description', 'file']
        fields.extend([f.getName() for f in schema.fields()])
        return fields

    def get_required_fields(self):
        return ['file', 'fileDate']

    def get_errors_list(self):
        """ The list of potential errors to display in the form.
        """
        lang = self.lang()
        
        # The list of potentials errors for each field.
        no_file = translate(_(u'msg_error_no_file',
                               default=u'You must provide a file'),
                             target_language=lang)

        invalid = translate(_p(u'error_invalid_date'),
                               target_language=lang)
        return {'file' : {'no_file': no_file},
                'fileDate' : {'invalid' : invalid}
                }

    def validate_form(self):
        """ Validates the form submitted when updating the employee.
        """
        fields = self.get_form_fields()
        for field in fields:
            if not field in self.form and not field == 'file':
                # Should not happen
                return

        if ('file' in self.form and not self.form['file']) and \
               not ('file_delete' in self.form and \
                    self.form['file_delete'] == 'file_nochange'):
            self.errors.append('file_no_file')

        try:
            year = int(self.form['fileDate_year'])
            month = int(self.form['fileDate_month'])
            day = int(self.form['fileDate_day'])
            DateTime(year, month, day)
        except:
            self.errors.append('fileDate_invalid')

        if self.errors:
            self.form['file'] = self.context.getFile()

    def next_url(self):
        """ Redirects to the absence view, not file view.
        """
        return self.absence.absolute_url()

    def __init__(self, context, request):
        success_msg = _(u'msg_file_saved',
                        default=u'The file has been saved.')

        error_msg = _(u'error_file_saved',
                        default=u'Errors were found while saving the file.')

        BaseEditView.__init__(self, context, request, schema,
                              success_msg, error_msg)

        self.absence = aq_parent(context)
