# -*- coding: UTF-8 -*-
#    This file is part of arena.
#
#    arena 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 3 of the License or, at your
#    option, any later version.
#
#    arena is distributed in the hope that it will be useful, but
#    WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABLITY
#    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 arena.  If not, see <http://www.gnu.org/licenses/>.

## @file
#  This file defines a class to manage a single post.

from Library.DataSource.DataRows import ADataRowWithExpandingFields
from Library.IO.Logging.Logs import AMessageWithTimeStamp
from Library.String.Utilities import String
from Library.UI.Channels import chMetaItemsSeparator, \
    chMetaKeysValuesSeparator

## Events generated by APost
postEvents = {
    # Before post content is parsed
    "parseContent": None
}

## Represents an error that may occur with a post.
class APostError(AMessageWithTimeStamp):
    pass
       
## This class represents a single post within a channel.  It allows the
#  contents of the post to be parsed before the post is displayed to the end
#  user.
class APost(ADataRowWithExpandingFields):
    ## Constructor
    def __init__(Self, fieldsValues=None, **params):
        # Set up our expanding field
        if "expand" in params:
            params["expand"].update({
                "meta": (dict, chMetaKeysValuesSeparator, chMetaItemsSeparator)
            })
            
        else:
            params.update({
                "expand": {
                    "meta": (dict, chMetaKeysValuesSeparator, chMetaItemsSeparator)
                }
            })
        
        ADataRowWithExpandingFields.__init__(Self, fieldsValues, **params)      
        
    ## Initializer
    def init(Self):
        result = ADataRowWithExpandingFields.init(Self)
        
        if result:
            # Establish private attributes
            # Post metadata
            Self._meta = {}
            # The parsed content of the post
            Self._parsedContent = None
            
            # Update the events generated by the class
            Self._events.update(postEvents)
            
        return result
        
    ## Flush changes made to the post record back to the data source
    def flush(Self, *criteria):
        if len(Self._changes) > 0:
            cri = list(criteria)
            if len(cri) == 0:
                cri.append(("{field:id} = {}", Self["id"]))
                
            # Remove the "id" field since it is immutable and the data source
            # will complain if we attempt to update it
            pid = Self._fieldsValues["id"]          
            del Self._fieldsValues["id"]
            
            ADataRowWithExpandingFields.flush(Self, *cri)    
            
            # Restore the "id" field
            Self._fieldsValues["id"] = pid  
        
    ## Publish a post
    def publish(Self):
        pass              
        
    ## Parse the contents of the post.
    #
    #  Descendant classes should override this method to parse the contents
    #  of the post before it is displayed to the end user.
    #
    #  This function should return a string.
    def parseContent(Self):
        result = ""
        
        Event = Self.generate("parseContent")
        if Event.handled():
            result = Event.result()
            
        del Event
        
        return result
        
    # Properties ---------------------------------------------------------------             
    ## Retrieve the parsed content of the post
    def parsedContent(Self):
        if Self._parsedContent is None:
            Self._parsedContent = Self.parseContent()
            
        return Self._parsedContent

