# -*- coding: utf-8 -*-
"""Mixed Mark"""

__author__  = 'Kenji Saito <ksaito@do-johodai.ac.jp>'
#__docformat__ = 'plaintext'

from AccessControl import ClassSecurityInfo

try:
  from Products.LinguaPlone.public import *
except ImportError:
  # No multilingual support
  from Products.Archetypes.public import *

from Products.MixedMark.interfaces import IMixedMark

from Products.ATContentTypes.content.document import ATDocument
from Products.ATContentTypes.content.document import finalizeATCTSchema

from Products.Archetypes.Marshall import RFC822Marshaller
import os, string

# Copy the ATDocument schema (to avoid modifying the original) and append our
# own fields for the images and attachments manager widgets.
MixedMarkSchema = ATDocument.schema.copy() + Schema((
        LinesField('css',
                  searchable=0,
                  required=0,
                  primary=0,
                  widget=LinesWidget(label='css',rows=2,columns=80),
                  ),
        LinesField('s5style',
                  searchable=0,
                  required=0,
                  primary=0,
                  widget=LinesWidget(label='s5style',rows=2,columns=80),
                  ),
        TextField('notation3',
                  searchable=1,
                  required=0,
                  primary=0,
                  widget=TextAreaWidget(label='notation3',rows=5),
                  ),
        TextField('text',
                  searchable=1,
                  required=1,
                  primary=1,
                  widget=TextAreaWidget(label='Body',rows=30),
                  ),
    ),
    marshall=RFC822Marshaller(),
    )

# Finalise the schema according to ATContentTypes standards. This basically
# moves the Related items and Allow discussion fields to the bottom of the
# form. See ATContentTypes.content.schemata for details.
finalizeATCTSchema(MixedMarkSchema)

mm2xhtmlCommandBody = '/usr/local/bin/mm2xhtml -body'
mm2xhtmlCommandS5 = '/usr/local/bin/mm2xhtml -s5'

def addHeader(instance, inText):
    h = ''
    if len(instance.css)>0:
        h = h + 'css:'
        for c in instance.css:
            h = h + '  ' + str(c) + '\n'
    if len(instance.s5style)>0:
        h = h + 's5style:'
        for s in instance.s5style:
            h = h + '  ' + str(s) + '\n'
    n = str(instance.notation3).split('\n')
    if len(n)>0:
        h = h + 'notation3:'
        for n in str(instance.notation3).split('\n'):
            h = h + '  ' + n + '\n'
    h = h + '\n'
    return h + inText

def mm2xhtmlBody(instance, inText):
    inText = addHeader(instance, inText)
    input, output = os.popen2(mm2xhtmlCommandBody)
    input.write(inText)
    input.close()
    return output.read()

def mm2xhtmlS5(instance, inText):
    inText = addHeader(instance, inText)
    input, output = os.popen2(mm2xhtmlCommandS5)
    input.write(inText)
    input.close()
    return output.read()

class MixedMark(ATDocument):
    """
    MixedMark
    """

    # Standard content type setup
    portal_type = meta_type = 'MixedMark'
    archetype_name = 'MixedMark'
    #content_icon = 'RichDocument.gif'
    schema = MixedMarkSchema
    typeDescription= 'MixedMark'
    typeDescMsgId  = 'MixedMark'

    # Set up our views - these are available from the 'display' menu
    default_view = 'mixedmark_view'
    immediate_view = 'mixedmark_view'
    suppl_views = ('mixedmark_iframe', 'mixedmark_main', 'mixedmark_s5')

    # Make sure we get title-to-id generation when an object is created
    _at_rename_after_creation = True

    # Make sure we get all the interface declarations from ATDocument,
    # which includes support for ISelectableBrowserDefault to get the
    # 'display' menu to work, IHistoryAware and other standard interfaces.
    # In addition, add INonStructuralFolder to tell Plone that even though
    # this type is technically a folder, it should be treated as a standard
    # content type. This ensures the user doesn't perceive a RichDocument as
    # a folder.
    __implements__ = ATDocument.__implements__ + \
                     (IMixedMark,)

    # Get the standard actions (tabs)
    actions = ATDocument.actions
    #actions = ({
    #    'id': 'view',
    #    'name': 'View',
    #    'action': 'string:${object_url}/mixedmark_view',
    #    'permissions': (CMFCorePermissions.View,)
    #    },)

    # This method, from ISelectableBrowserDefault, is used to check whether
    # the "Choose content item to use as deafult view" option will be 
    # presented. This makes sense for folders, but not for RichDocument, so
    # always disallow
    def canSetDefaultPage(self):
        return False

    # enable FTP/WebDAV and friends
    PUT = ATDocument.PUT

    def getHTMLBody(self):
        mm = self.getRawText()
        return mm2xhtmlBody(self, mm)

    def getS5(self):
        mm = self.getRawText()
        return mm2xhtmlS5(self, mm)

    def getCSS(self):
        mm = ''
        if len(self.css)>0:
            for c in self.css:
                mm = mm + '<link rel="stylesheet" type="text/css" href="%s" />\n' % str(c)
        return mm

    def CookedBody(self, stx_level=None, setlevel=0):
        mm = self.getRawText()
        return mm2xhtmlBody(self, mm)

registerType(MixedMark)
