class Dunlop::SourceFilesController < Dunlop::ApplicationController
  respond_to :html

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

  def show
    @source_file = SourceFile.find(params[:id])
    authorize! :read, @source_file
    respond_with(@source_file)
  end

  def new
    @source_file = SourceFile.new
    authorize! :manage, @source_file
    respond_with(@source_file)
  end

  def create
    @source_file = SourceFile.factory(source_file_params)
    redirect_to source_files_path, alert: "No file given" and return unless params[:source_file][:original_file].present?
    redirect_to source_files_path, alert: "No type specified" and return unless params[:source_file][:sti_type].present?
    authorize! :manage, @source_file
    @source_file.creator = current_user
    @source_file.save && @source_file.autoload!
    redirect_to source_files_path
  end

  def destroy
    @source_file = SourceFile.find(params[:id])
    authorize! :manage, @source_file
    @source_file.destroy
    redirect_to source_files_path
  end

  def download
    @source_file = SourceFile.find(params[:id])
    authorize! :download, @source_file
    return redirect_back(fallback_location: source_files_path, alert: "File is no longer present") unless @source_file.original_file.present?
    Dunlop::FileDownload.create user: current_user, file: @source_file
    send_file @source_file.original_file.path
  end

  def schedule
    @source_file = SourceFile.find(params[:id])
    authorize! :manage, @source_file
    @source_file.scheduled!
    flash[:notice] = "Successfully scheduled loading of source file"
    redirect_to source_files_path
  end

  private

  def source_file_params
    params.require(:source_file).permit(:sti_type, :original_file)
  end

end
