# encoding: utf-8
#####leave message   fq
class WordsController < ApplicationController
  
  before_filter :find_user, :only => [:new, :create, :destroy, :more, :back]
  def create
    if params[:new_form][:user_message].size>0
      unless params[:user_id].nil?
        if params[:reference_content]
          message = params[:new_form][:user_message] + "\n" + params[:reference_content]
        else
          message = params[:new_form][:user_message]
        end
        refer_user_id = params[:new_form][:reference_user_id].to_i
        
        @user.add_jour(User.current, message, refer_user_id)
        unless refer_user_id == 0 || refer_user_id == User.current.id
          User.find(refer_user_id).add_jour(User.current, message, refer_user_id)
        end
        @user.count_new_jour
        # if a_message.size > 5
          # @message = a_message[-5, 5]
        # else
          # @message = a_message
        # end
        # @message_count = a_message.count
      end
    end
    @jours = @user.journals_for_messages.where('m_parent_id IS NULL').reverse
    @limit =  10
    @feedback_count = @jours.count
    @feedback_pages = Paginator.new @feedback_count, @limit, params['page']
    @offset ||= @feedback_pages.offset
    @jour = @jours[@offset, @limit]

    respond_to do |format|
     # format.html { redirect_to_referer_or {render :text => 'Watcher added.', :layout => true}}
      format.js
      #format.api { render_api_ok }
    end
  end

  
  def create_reply
    # 这里是创建回复所使用的方法，此方法只针对回复，每一个新的留言并不在此方法管理范围内。
    # 由于多个地方用到了留言，而之前的表设计也有jour_type/jour_id这类信息
    # 所以在方法 add_reply_adapter 中判断所有调用此方法的来源页面，
    # 为了保证兼容以往所有的代码，保证以往的方法可以调用，在返回页面中都做了各式各样的判断。
    # 页面保证 render new_respond/journal_reply
    # 修改 add_reply_adapter 中可以确保留言创建成功
    # 删除留言功能要调用destroy，也记得在destroy.js中修改

    # deny api. api useless
    parent_id = params[:reference_id]
    author_id = User.current.id
    reply_user_id = params[:reference_user_id]
    reply_id = params[:reference_message_id] # 暂时不实现
    content = params[:user_notes]
    options = {:user_id => author_id, 
              :m_parent_id => parent_id,
              :m_reply_id => reply_id,
              :reply_id => reply_user_id,
              :notes => content, 
              :is_readed => false}
    @jfm = add_reply_adapter options

    respond_to do |format|
      # format.html {
      #   if @jfm.errors.empty?
      #     flash.now.notice = l(:label_feedback_success)
      #   else
      #     flash.now.errors = l(:label_feedback_fail)
      #   end
      #   render 'test/index'
      # }
      format.js{
        @save_succ = true if @jfm.errors.empty?
      }
    end
  end
  
  def destroy
    @journal_destroyed = JournalsForMessage.delete_message(params[:object_id])
    
    respond_to do |format|
      format.js
      #format.api { render_api_ok }
    end
  end
  
  def new
    @jour = JournalsForMessage.find(params[:journal_id]) if params[:journal_id]
    if @jour
      user = @jour.user
      text = @jour.notes
    else
      user = @user
      text = []
    end
    # Replaces pre blocks with [...]
    text = text.to_s.strip.gsub(%r{<pre>((.|\s)*?)</pre>}m, '[...]')
    @content = "> #{ll(User.current.language, :text_user_wrote, user)}\n> "
    @content << text.gsub(/(\r?\n|\r\n?)/, "\n> ") + "\n\n"
        
    # @content << text.gsub(/(\r?\n|\r\n?)/, "\n> ") + "\n\n"
    # @content = "> #{ll(Setting.default_language, :text_user_wrote, user)}\n> "
    
    @id = user.id
  rescue ActiveRecord::RecordNotFound
    render_404
  end
  
  def more
    @jours = @user.journals_for_messages.reverse
    @limit =  10
    @feedback_count = @jours.count
    @feedback_pages = Paginator.new @feedback_count, @limit, params['page']
    @offset ||= @feedback_pages.offset
    @jour = @jours[@offset, @limit]
    @state = true
    
    respond_to do |format|
      format.html { redirect_to :back }
      format.js
      #format.api { render_api_ok }
    end
  end
  
  def back
    @jours = @user.journals_for_messages.reverse
    @limit =  10
    @feedback_count = @jours.count
    @feedback_pages = Paginator.new @feedback_count, @limit, params['page']
    @offset ||= @feedback_pages.offset
    @jour = @jours[@offset, @limit]
    @state = false
    
    respond_to do |format|
      format.html { redirect_to :back }
      format.js
      #format.api { render_api_ok }
    end
  end
  
  def add_project_respond
    user = User.current
    message = params[:new_form][:project_message]
    Project.add_jour(user, message)
    
    redirect_to project_feedback_path('trustie')
    # redirect_to signin_path
  end
  
  def leave_project_message
    user = User.current
    message = params[:new_form][:project_message]
    feedback = Project.add_new_jour(user, message, params[:id])
    if(feedback.errors.empty?)
      redirect_to project_feedback_path(params[:id]), notice: l(:label_feedback_success)
    else
      flash[:error] = feedback.errors.full_messages[0]
      redirect_to project_feedback_path(params[:id])
    end

  end
  
  def add_brief_introdution
    user = User.current
    message = params[:new_form][:user_introduction]
    UserExtensions.introduction(user, message)
    redirect_to user_path(user.id)
  end
  
  private

  def find_user
    if params[:user_id]
      @user = User.find(params[:user_id])
    end
  rescue
    render_404
  end
  
  def obj_distinguish_url_origin
    referer = request.headers["Referer"]
    obj_id = referer.match(%r(/([0-9]{1,})(/|$)))[1]
    if referer.match(/project/)
      obj = Project.find_by_id(obj_id)
    elsif referer.match(/user/)
      obj = User.find_by_id(obj_id)
    elsif ( referer.match(/bids/) || referer.match(/calls/) )
      obj = Bid.find_by_id(obj_id)
    elsif ( referer.match(/contests/) || referer.match(/contests/) )   #new added
      obj = Contest.find_by_id(obj_id)
    elsif ( referer.match(/softapplications/) || referer.match(/softapplications/) )   #new added
      obj = Softapplication.find_by_id(obj_id)    
    else
      raise 'create reply obj unknow type.'
    end
    obj
  end

  def add_reply_adapter options
    obj = obj_distinguish_url_origin
    if obj.kind_of? User
      obj.add_jour(nil, nil, nil, options)
    elsif obj.kind_of? Project
      Project.add_new_jour(nil, nil, obj.id, options)
    elsif obj.kind_of? Bid
      obj.add_jour(nil, nil, nil, options)
    elsif obj.kind_of? Contest
      obj.add_jour(nil, nil, obj.id, options)   #new added
    elsif obj.kind_of? Softapplication
      obj.add_jour(nil, nil, obj.id, options)   #new added      
    else
      raise 'create reply obj unknow type.'
    end
  end
  #######end of message
end