# -*- coding: iso-8859-15 -*-


# Glasnost
# By: Odile Bénassy <obenassy@entrouvert.com>
#     Romain Chantereau <rchantereau@entrouvert.com>
#     Nicolas Clapiès <nclapies@easter-eggs.org>
#     Pierre-Antoine Dejace <padejace@entrouvert.be>
#     Thierry Dulieu <tdulieu@easter-eggs.com>
#     Florent Monnier <monnier@codelutin.com>
#     Cédric Musso <cmusso@easter-eggs.org>
#     Frédéric Péters <fpeters@entrouvert.be>
#     Benjamin Poussin <poussin@codelutin.com>
#     Emmanuel Raviart <eraviart@entrouvert.com>
#     Sébastien Régnier <regnier@codelutin.com>
#     Emmanuel Saracco <esaracco@easter-eggs.com>
#
# Copyright (C) 2000, 2001 Easter-eggs & Emmanuel Raviart
# Copyright (C) 2002 Odile Bénassy, Code Lutin, Thierry Dulieu, Easter-eggs,
#     Entr'ouvert, Frédéric Péters, Benjamin Poussin, Emmanuel Raviart,
#     Emmanuel Saracco & Théridion
# Copyright (C) 2003 Odile Bénassy, Romain Chantereau, Nicolas Clapiès,
#     Code Lutin, Pierre-Antoine Dejace, Thierry Dulieu, Easter-eggs,
#     Entr'ouvert, Florent Monnier, Cédric Musso, Ouvaton, Frédéric Péters,
#     Benjamin Poussin, Rodolphe Quiédeville, Emmanuel Raviart, Sébastien
#     Régnier, Emmanuel Saracco, Théridion & Vecam
#
# 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.


__doc__ = """Glasnost Virtual Hosts Common Models"""

__version__ = '$Revision$'[11:-2]

import os
import sgmllib

from ObjectsCommon import AdminCommon, ObjectCommon, ObjectsCommonMixin
import system

import glasnost.common.context as context
import glasnost.common.tools_new as commonTools

class AdminVirtualHostsCommon(AdminCommon):
    defaultVirtualHostId = None
    defaultVirtualHostId_kind_balloonHelp = N_(
        'Select the default virtual host to use on this server')
    defaultVirtualHostId_kind_label = N_('Default Virtual Host')
    defaultVirtualHostId_kind_serverRoles = ['virtualhosts']
    defaultVirtualHostId_kindName = 'Id'

    serverRole = 'virtualhosts'

    def getOrderedLayoutSlotNames(self, parentSlot = None):
        slotNames = AdminCommon.getOrderedLayoutSlotNames(
            self, parentSlot = parentSlot)
        slotNames += ['defaultVirtualHostId']
        return slotNames


class VirtualHostInfoParser(sgmllib.SGMLParser):
    inLabel = 0
    label = None
    def __init__(self, body):
        sgmllib.SGMLParser.__init__(self)
        self.feed(body)

    def start_label(self, attrs):
        if len(attrs) == 0:
            self.inLabel = 1
            self.label = ''

    def end_label(self):
        self.inLabel = 0
        if self.label:
            self.label = self.label.strip()

    def handle_data(self, data):
        if self.inLabel:
            self.label += data


class ProfileParser(sgmllib.SGMLParser):
    inDescription = 0
    description = None
    def __init__(self, body):
        sgmllib.SGMLParser.__init__(self)
        self.feed(body)

    def start_description(self, attrs):
        if len(attrs) == 0:
            self.inDescription = 1
            self.description = ''

    def end_description(self):
        self.inDescription = 0
        if self.description:
            self.description = self.description.strip()

    def handle_data(self, data):
        if self.inDescription:
            self.description += data


class VirtualHostCommon(ObjectCommon):
    """Virtual host super class used to be inherited with a Mixin Class.

    This is the definition of the attributes of a virtual host object.
    This object is used by the VirtualHostProxy.

    """

    creationTime = None
    creationTime_kindName = 'CreationTime'

    customWebs = None
    customWebs_kind_importExport = 'from-server-only'
    customWebs_kind_keyKind_valueName = 'String'
    customWebs_kind_valueKind_valueName = 'String'
    customWebs_kind_stateInViewMode = 'hidden'
    customWebs_kind_stateInEditMode = 'hidden'
    customWebs_kindName = 'Mapping'

    locales = None
    locales_kind_itemKind_valueName = 'String'
    locales_kind_importExport = 'from-server-only'
    locales_kind_stateInViewMode = 'hidden'
    locales_kind_stateInEditMode = 'hidden'
    locales_kindName = 'Sequence'

    defaultDispatcherId = None
    defaultDispatcherId_kind_balloonHelp = N_(
            'Enter the Glasnost dispatcher [id->virtualhost-creation] for this '\
            'virtual host.')
    defaultDispatcherId_kind_defaultValue = 'glasnost://localhost'
    defaultDispatcherId_kind_isModifiable = 0
    defaultDispatcherId_kind_isRequired = 1
    defaultDispatcherId_kind_label = N_('Glasnost Dispatcher ID')
    defaultDispatcherId_kind_stateInCreateMode = 'read-write'
    defaultDispatcherId_kind_stateInEditMode = 'read-only'
    defaultDispatcherId_kind_widget_size = 40
    defaultDispatcherId_kind_widgetName = 'InputText'
    defaultDispatcherId_kindName = 'DispatcherId'

    hostName = None
    hostName_kind_balloonHelp = N_('Enter the host name.')
    hostName_kind_isRequired = 1
    hostName_kind_isTranslatable = 0
    hostName_kind_label = N_('Web Host Name')
    hostName_kind_widget_size = 40
    hostName_kind_widgetName = 'Url'
    hostName_kindName = 'String'

    modificationTime = None
    modificationTime_kindName = 'ModificationTime'

    profiles = None
    class profiles_kindClass:
        _kindName = 'Sequence'
        defaultValue = ['basic', 'cms', 'vote']
        minCount = 1
        label = N_('Usage Profiles')
        class itemKind_valueClass:
            _kindName = 'Choice'
            def getLabels(self, slot):
                profilesPath = os.path.join(commonTools.configDir, 'profiles')
                profiles = self.getValues(slot)
                labels = {}
                for p in profiles:
                    pFileName = os.path.join(profilesPath, p + '.xml')
                    label = ProfileParser(open(pFileName).read()).description
                    labels[p] = label
                return labels

            def getSortedValues(self, slot):
                # puts 'basic' first
                values = self.getValues(slot)
                values.sort()
                values.remove('basic')
                values.insert(0, 'basic')
                return values
                
            def getValues(self, slot):
                profilesPath = os.path.join(commonTools.configDir, 'profiles')
                profiles = os.listdir(profilesPath)
                values = [x[:-4] for x in profiles if x.endswith('.xml')]
                return values

        widgetName = 'MultiCheck'

    readersSet = None
    # FIXME: Which of the following lines is correct?
    readersSet_defaultValue = [system.generalPublicId]
    # readersSet_kind_itemKind_value_defaultValue = system.generalPublicId
    readersSet_kindName = 'ReadersSet'

    serverRole = 'virtualhosts'

    templateDirectoryName = 'glasnost2'
    class templateDirectoryName_kindClass:
        _kindName = 'Choice'
        balloonHelp = N_('Select the template (skin) to use for this host.')
        isRequired = 1
        defaultValue = 'glasnost2'
        label = N_('Template')
        def getValues(self, slot):
            templatesDirectoryPath = context.getVar('templatesDirectoryPath')
            dirs = os.listdir(templatesDirectoryPath)
            values = []
            for d in dirs:
                infosName = os.path.join(templatesDirectoryPath, d, 'infos.xml')
                if os.path.exists(infosName):
                    values.append(d)
            values.sort()
            return values

        def getLabels(self, slot):
            templatesDirectoryPath = context.getVar('templatesDirectoryPath')
            dirs = self.getValues(slot)
            labels = {}
            for d in dirs:
                infosName = os.path.join(templatesDirectoryPath, d, 'infos.xml')
                label = VirtualHostInfoParser(open(infosName).read()).label
                labels[d] = label
            return labels

    title = None
    title_kind_balloonHelp = N_('Enter the [title->virtualhost-creation] of this '\
            'virtual host.')
    title_kind_isRequired = 1
    title_kind_label = N_('Title')
    title_kind_widget_size = 40
    title_kindName = 'String'

    writersSet = None
    writersSet_kindName = 'WritersSet'

    def getLabel(self):
        """Return the virtual host title name string.

        Return the title string attribute.
        If the title string is None, an empty string is returned.
        
        """
        
        label = self.getTitle()
        if label is None:
            return ''
        return label

    def getOrderedLayoutSlotNames(self, parentSlot = None):
        """Return the layout slots names sequences.
        
        The layout slots names of the parent are taken, and to them, the
        class slot names are added.

        Keyword argument
        ================

        *parentSlot*:
            The slot where the object is instanciated.

        Return the slot names sequence, minimum slot names are the current
        object slots.
        
        """
        
        slotNames = ObjectCommon.getOrderedLayoutSlotNames(
            self, parentSlot = parentSlot)
        slotNames += [
            'title', 'defaultDispatcherId', 'hostName',
            'templateDirectoryName', 'creationTime', 'modificationTime',
            'writersSet', 'readersSet']
        return slotNames

    def getTitle(self):
        """Return the title attribute."""

        return self.title


class VirtualHostsCommonMixin(ObjectsCommonMixin):
    
    """Abstract class designed to be inherited with another class.

    The product of a multiple inheritance is a fonctionnal Virtual host
    server/proxy.
    All methods can be overriden or extended, in fact, this class define their
    default behavior.

    Attributes:
    ===========

    *adminClassName*:
        The class name string used for administrative purposes.
        
    *newObjectNameCapitalized*:
        The illustrating string explaining what do a new object creation.
        The objects are the objects handled by the subclass (not the class
        itself).
        
    *objectClassName*:
        The handled object class name string.
    
    *objectName*:
        The 'gettextized' handled object class name string.
    
    *objectNameCapitalized*:
        The capitalized 'gettextized' handled object class name string.
    
    *objectsName*:
        The 'gettextized' functionnal class name string (Usually the class name
        without the type (proxy or server, etc...)).
        
    *objectsNameCapitalized*:
        The capitalized 'gettextized'  class name string (Usually the class name
        without the type (proxy or server, etc...)).
    
    *serverRole*:
        The class server role string.
    
    """

   
    adminClassName = 'AdminVirtualHosts'
    newObjectNameCapitalized = N_('New Virtual Host')
    objectClassName = 'VirtualHost'
    objectName = N_('virtual host')
    objectNameCapitalized = N_('Virtual Host')
    objectsName = N_('virtual hosts')
    objectsNameCapitalized = N_('Virtual Hosts')
    serverRole = 'virtualhosts'

