class Panel::Announcement::BackEnd::BulletinsController < OrbitBackendController
  # include OrbitControllerLib::DivisionForDisable

  before_filter :clean_values, :only => [:create, :update]

  open_for_visitor :only => [:index, :show, :get_sorted_and_filtered_bulletins]

  before_filter :only => [ :new, :create, :edit, :update ] do |controller|
    @categories = get_categories_for_form
  end

  def preview
    bulletin = Bulletin.new params
    @preview_obj = bulletin.to_preview
    @preview_obj.save
    render '/shared/preview/preview.html.erb',:layout=>false
  end


  def index
    @tags = get_tags
    @categories = get_categories_for_index
    @statuses = get_statuses
    category_ids = @categories.collect{|t| t.id}

    @bulletins = get_sorted_and_filtered("bulletin", :category_id.in => category_ids)
    respond_to do |format|
      format.html # index.html.erb
      format.js { }
      format.xml  { render :xml => @bulletins }
    end
  end

  # GET /bulletins/1
  # GET /bulletins/1.xml
  def show
    @bulletin = Bulletin.find(params[:id])
    @tags = get_tags

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @bulletin }
    end
  end

  # GET /bulletins/new
  # GET /bulletins/new.xml
  def new
    if(session[:in_validate_object].blank?)
      @bulletin = Bulletin.new(:postdate => DateTime.now)
    else
      @bulletin = session[:in_validate_object]
      session[:in_validate_object] = {}
    end

    @link_url = panel_announcement_back_end_bulletins_path
    @tags = get_tags
    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @bulletin }
    end
  end

  # GET /bulletins/1/edit
  def edit
    @bulletin = Bulletin.find(params[:id])
    if !current_user.admin? && (@bulletin.is_rejected? || @bulletin.is_checked?)
      redirect_to :action => :index
    else
      # @summary_variable = @bulletin.summary_variable

      @link_url = panel_announcement_back_end_bulletin_path(@bulletin)

      @tags = get_tags
    end
  end

  # POST /bulletins
  # POST /bulletins.xml
  def create
    @tags = get_tags
    @bulletin = Bulletin.new(params[:bulletin])
    @bulletin.deadline = nil if (@bulletin.deadline < @bulletin.postdate rescue nil)

    @bulletin.create_user_id = current_user.id
    @bulletin.update_user_id = current_user.id
    if(is_manager? || is_admin?)
      @bulletin.is_checked = true
      @bulletin.is_rejected = false
      @bulletin.de_pending
    end

    respond_to do |format|
      if @bulletin.save

        format.html { redirect_to(panel_announcement_back_end_bulletins_url, :notice => t('announcement.create_bulletin_success')) }
        format.xml  { render :xml => @bulletin, :status => :created, :location => @bulletin }
        # format.js
        format.js { 
          @info = {"success"=>"true","redirect_url"=>panel_announcement_back_end_bulletins_url}
          flash[:notice] = t('bulletin.create_bulletin_success')
          render "/shared/preview/after_create.js.erb"
        }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @bulletin.errors, :status => :unprocessable_entity }
        format.js { 
          @info = {"success"=>"false","redirect_url"=>new_panel_announcement_back_end_bulletin_url(:bulletin => @bulletin)}
          session[:in_validate_object] = @bulletin
          render "/shared/preview/after_create.js.erb"
        }
      end
    end
  end

  # PUT /bulletins/1
  # PUT /bulletins/1.xml

  def update

      @bulletin = Bulletin.find(params[:id])

      # @bulletin.image.clear if params[:bulletin][:image_del] == '1'
      # if params[:bulletin][:image_del] == '1' 
      # @bulletin.remove_image!
      # @bulletin.image_del = nil
      # params[:bulletin][:image_del] = nil
      # end


      delete_out_invalid_date_from_params
      respond_to do |format|

        if @bulletin.update_attributes(params[:bulletin])
          if(is_manager? || is_admin?)
            @bulletin.is_checked = true
            @bulletin.is_rejected = false
            @bulletin.de_pending!
          end
          # if (params[:bulletin][:is_checked] == "false")
          #   @bulletin.is_rejected = true
          #   @bulletin.save!
          # end
          # if (@bulletin.deadline < @bulletin.postdate rescue nil)
          #    @bulletin.deadline = nil
          #    @bulletin.update_user_id = current_user.id
          #    @bulletin.save!
          #  end
          # format.html { redirect_to(panel_announcement_back_end_bulletin_url(@bulletin), :notice => t('bulletin.update_bulletin_success')) }
          format.html { redirect_to(panel_announcement_back_end_bulletins_url, :notice => t('bulletin.update_bulletin_success')) }
          format.js  { render 'toggle_enable' }
          format.xml  { head :ok }
        else
          @tags = get_tags
          format.html { render :action => "edit" }
          format.xml  { render :xml => @bulletin.errors, :status => :unprocessable_entity }
        end
      end

    end

  # DELETE /bulletins/1
  # DELETE /bulletins/1.xml
  def destroy
    @bulletin = Bulletin.find(params[:id])
    # @bulletin.bulletin_files.destroy
    @bulletin.destroy

    respond_to do |format|

      format.html { redirect_to(panel_announcement_back_end_bulletins_url) }
      # format.xml  { head :ok }
      format.js
    end
  end

  def delete
    if params[:ids]
      bulletins = Bulletin.any_in(:_id => params[:ids]).destroy_all
    end
    redirect_to panel_announcement_back_end_bulletins_url(:filter => params[:filter], :direction => params[:direction], :sort => params[:sort], :sort_options => params[:sort_options])
  end


  protected

  def delete_out_invalid_date_from_params
    if((params[:bulletin]["deadline(1i)"] && params[:bulletin]["deadline(1i)"].blank?) or (params[:bulletin]["deadline(2i)"] && params[:bulletin]["deadline(2i)"].blank?) or (params[:bulletin]["deadline(3i)"] && params[:bulletin]["deadline(3i)"].blank?)) 
      params[:bulletin].delete("deadline(1i)")
      params[:bulletin].delete("deadline(2i)")
      params[:bulletin].delete("deadline(3i)")
      params[:bulletin].delete("deadline(4i)")
      params[:bulletin].delete("deadline(5i)")
      @bulletin.deadline = nil
    end rescue nil
  end

  def clean_values
    if params[:bulletin]
      params[:bulletin][:bulletin_links_attributes].each_with_index do |link, index|
        params[:bulletin][:bulletin_links_attributes].delete(index.to_s) if link[1]['url'].blank? and link[1]['title_translations'].blank?
      end rescue nil
      params[:bulletin][:bulletin_files_attributes].each_with_index do |link, index|
        params[:bulletin][:bulletin_files_attributes].delete(index.to_s) if link[1]['file'].blank? and link[1]['title_translations'].blank?
      end rescue nil
    end
  end
end
