page_templates_controller.rb 2.81 KB
module Kanjai
  class Admin::PageTemplatesController < AdminController

    before_action :set_s3_direct_post, only: [:edit, :update]

    after_action :unzip_content, only: [:update]

    def index
      @collection = PageTemplate.order(:title)
    end

    def new
      @page_template = PageTemplate.new
      render :layout => false
    end

    def create
      @page_template = PageTemplate.new(permitted_params[:page_template])

      if @page_template.save
        render :partial => 'kanjai/admin/page_templates/create/success'
      else
        render :partial => 'kanjai/admin/page_templates/create/error'
      end
    end

    def edit
      @page_template = PageTemplate.find(params[:id])
      @url = @page_template.file_expiring_url
    end

    def update
      @page_template = PageTemplate.find(params[:id])
      @page_template.unzip = false

      if @page_template.update(permitted_params[:page_template])
        redirect_to admin_page_templates_url
      else
        render :action => :edit
      end

    end


    def destroy
      @page_template = PageTemplate.find(params[:id])
      @page_template.destroy

      render :json => {:status => 'ok'}.to_json
    end

    def marker
      lang = params[:lang]
      @page_template = PageTemplate.find(params[:id])
      if @page_template.unzip
        exist_markers = @page_template.page_content_markers.where(lang: lang).collect(&:marker)

        @page_template.template_statics.where.not(marker: exist_markers).each do |item|
          @page_template.page_content_markers.create(
                      marker: item.marker,
                      marker_type: item.marker_type,
                      marker_name: item.marker_name,
                      lang: lang
          )
        end



        @markers = @page_template.page_content_markers.where(lang: lang)
      else
        flash[:notice] = "Template must be unzip before edit static element"
        redirect_to action: :index
      end
    end

    def update_marker
      @page_template = PageTemplate.find(params[:id])
      if @page_template.update(permitted_params[:page_template])
        redirect_to :action => :index
      else
        redirect_to :action => :marker
      end
    end

    private

    def permitted_params
      params.permit(:page_template => [:title, :attachment_file_name,
                                       page_content_markers_attributes: [:id, :page_content_id, :marker, :text_value, :attachment_file_name]
                    ])
    end

    def unzip_content
      if @page_template.unzip == false
        @page_template.unzip_content
      end
    end

    def set_s3_direct_post
      page_template = PageTemplate.find(params[:id])
      @s3_direct_post = S3_BUCKET.presigned_post(key: "#{page_template.get_file_path}${filename}", success_action_status: '201', acl: 'private')
    end

  end
end