class Dunlop::TargetFilesController < Dunlop::ApplicationController
  skip_authorize_resource if respond_to?(:skip_authorize_resource)
  before_action :find_target_file, except: [:index, :download_latest]

  def index
    authorize! :index, TargetFile
    @q = TargetFile.where(sti_type: TargetFile.classes.select{|cls| can? :read, cls}.map(&:name)).search(query)
    @q.sorts = "created_at desc" if @q.sorts.empty?
    @target_files = @q.result.page(params[:page]).per(100)
  end

  def show
    authorize! :read, @target_file
  end

  def download
    authorize! :download, @target_file
    Dunlop::FileDownload.create user: current_user, file: @target_file
    send_file @target_file.original_file.path
  end

  def download_latest
    target_file_class = "TargetFile::#{params[:target_file_type].to_s.camelize}".safe_constantize
    @target_file = target_file_class.latest
    return head(:not_found) unless @target_file.present?
    authorize! :download, @target_file
    Dunlop::FileDownload.create user: current_user, file: @target_file
    send_file @target_file.original_file.path
  end

  def destroy
    authorize! :destroy, @target_file
    @target_file.destroy
    redirect_to dunlop.target_files_path, notice: t('action.destroy.successfull', model: @target_file.class.model_name.human)
  end

  private

  def find_target_file
    @target_file = TargetFile.find(params[:id])
  end

end
