# packages/notes/www/add-edit.tcl
ad_page_contract {
    @author Richard Hamilton (richard.hamilton@webteamworks.com)
    @creation-date 18-09-2005
    @cvs-id@ $Id$
    Intrasite Message message add/edit' page
} {
    {message_id:integer,notnull,optional}
    {original_message_id:integer,notnull,optional}
    {response:notnull,optional}
    {original_sender_user_id:notnull,optional}
    {original_message_id:notnull,optional}
} -properties {
    context:onevalue
}

# the unique identifier for this package
set package_id  [ad_conn package_id]
set package_url [ad_conn package_url]
set user_id     [ad_conn user_id]

# This script has to take care of all message creation and editing. Consequently it has
# to determine the following things:
#
#   1) Does the user 'own' the message.
#   2) Is the message editable or has it been sent already and is therefore 'cast in stone'.
#
# We also need to know what action is required:
#
#   a) Are we asking for a completely new message.
#   b) Are we asking to edit an existing message.
#   c) Do we want to forward a message to someone else.
#   d) Do we want to reply to the sender of a message.
#
# Just a reminder:
#
#   i) the package supports permissions at the package_id level
#   ii) the package is a singleton.

if {[info exists message_id]} {

    # Check permissions on the package_id
    ad_require_permission $package_id write

    # Check to make sure that this user owns the message. Users cannot edit each others' messages.
    db_1row message_author_p {
        select im_message__author_p(:message_id, :user_id) as message_author_p
    }
    
    if { [string is false $message_author_p] } {
        ad_script_abort
    }

    # Check to see if message has been sent already - of so cannot be changed.
    db_1row message_sent_p {
        select im_message__sent_p(:message_id) as message_sent_p
    }

    if { $message_sent_p == "t" } {
        ad_return_complaint 1 "This message is not editable - it has already been sent."
    }

    # If the request survives the preceeding tests then we are going to edit an existing message.
    set title "Edit Message"
    set context [list "Edit Message"]

} else {

    # Check permissions on the package_id
    ad_require_permission $package_id create
    
    # Assume a new message - if not code below will overwrite these values
    set title "New Message"
    set context [list "New Message"]
    
    # Find out whether we are creating a new message, a reply or a 'forward' and set page title accordingly.
    if { [exists_and_not_null original_message_id] && [exists_and_not_null response] } {

        if { $response == "reply" } {

            set title "Reply to Message"
            set context [list "Reply to Message"]

        } elseif { $response == "forward" } {

            set title "Forward Message"
            set context [list "Forward Message"]

        } else {

            ad_script_abort

        }
    }
}

template::form create new_message

if {[template::form is_request new_message] && [info exists message_id]} {

  # The user wants to edit an existing message.
  db_1row get_message {
    select subject, body, priority_p
    from im_message
    where message_id = :message_id
    and sender_user_id = :user_id
    and sent_p = false
    and deleted_p = false
  }

  template::element create new_message message_id \
      -widget hidden \
      -datatype number \
      -value $message_id

} else {

    if { [exists_and_not_null original_message_id] && [exists_and_not_null response] } {
        
        # The user wants to send a reply or forward a message.
        # Is the requesting user an addressee? If not, abort the script.
        db_1row original_message_addressee_p {
            select im_message__addressee_p(:original_message_id, :user_id) as original_message_addressee_p
        }

        if { [string is false $original_message_addressee_p] } { ad_script_abort }
        
        # Obtain the original message data. Note the by 'original' we mean the message to which you are currently 
        # replying, i.e. the immediate parent not the absolutely original message. In common with standard email
        # this package does not keep track of message threads.
        db_1row get_original_message {
        select m.subject, m.body, m.priority_p, m.sent_timestamptz, p.party_name as original_sender_name, m.sender_user_id as original_sender_user_id, im_to_addressees_horiz_list(m.message_id) as original_addressees
        from im_message m, party_names p
        where m.sender_user_id = p.party_id
        and message_id = :original_message_id
        and sent_p = true
        and deleted_p = false
        }

        # Now prepare the message content by indending and seperating the old content
        set modified_subject "Re: "
        append modified_subject $subject

        set temp_body [split $body "\n"]
        set body [concat "\n< Begin Reply Here >\n\n> --- Original Message ---\n>From: $original_sender_name\n>To: $original_addressees\n>Sent: $sent_timestamptz\n>\n>Subject: $subject\n>\n>" [join $temp_body "\n>"]]

        # If you're wondering why it is because the un-modified subject is needed in the preceeding statement!
        set subject $modified_subject

    } else {

        # The user wants to create a completely new message.
        set subject {}
        set body {}
        set priority_p 0
    }
}

template::element create new_message subject \
    -datatype text \
    -label "Subject" \
    -html { size 100 } \
    -value $subject
    
template::element create new_message body \
    -widget textarea \
    -datatype text \
    -label "Body" \
    -html { rows 35 cols 100 wrap soft } \
    -value $body

    # If the message is a reply, blank the priority variable.
if { [info exists response] } {
    set priority_p ""
}

template::element create new_message priority_p \
    -widget checkbox \
    -datatype boolean \
    -label "Priority" \
    -options { { High t } } \
    -value $priority_p
 
# Conditional on value of 'response' otherwise the template::element call will choke on the empty string.
if { [info exists response] } {

  template::element create new_message response \
      -widget hidden \
      -datatype string \
      -label "response" \
      -value $response

  template::element create new_message original_sender_user_id \
      -widget hidden \
      -datatype string \
      -label "original_sender_user_id" \
      -value $original_sender_user_id

  template::element create new_message original_message_id \
      -widget hidden \
      -datatype string \
      -label "original_message_id" \
      -value $original_message_id
} else {
    set response "new"
}

if [template::form is_valid new_message] {

  if { $response == "new" } {
      form get_values new_message subject body priority_p
  } else {
      form get_values new_message subject body priority_p response
  }

  set peeraddr [ad_conn peeraddr]

  if [info exists message_id] {
    db_dml update_message {
      update im_message
      set subject = :subject,
          body = :body,
          priority_p = :priority_p
      where message_id = :message_id
      and sender_user_id = :user_id
      and sent_p = false
      and deleted_p = false
    }
  } else {
    
    if { $response == "reply" } {
        
        # Create a new message that is a reply to the original message. The im_message__new_reply function
        # returns the message_id of the new message.
        db_1row message_new_reply {
            select im_message__new_reply( :user_id, :subject, :body, :priority_p, :original_sender_user_id, :original_message_id) as message_id
        }
    } else {
        # Create new message.  The im_message__new_reply function returns the message_id of the new message.
        db_1row message_new {
            select im_message__new( :user_id, :subject, :body, :priority_p)
        }
    }

  }

  ad_returnredirect "./message-display?message_id=$message_id"
}

set title [ad_quotehtml $title]

ad_return_template
