require_dependency "resque_jobs/job"

module ResqueJobs
  class JobsController < ResqueJobs::BaseController
    before_action :set_job, only: [:show, :destroy, :kill]

    def index
      authorize Job

      @jobs = Job.all(params)
    end

    def show
      respond_to do |format|
        format.html
        format.js
      end
    end

    def destroy
      if @job.destroy
        flash[:success] = "Job #{params[:id]} deleted"
      else
        flash[:error] = "Could not delete job #{params[:id]}"
      end

      redirect_to resque_jobs_jobs_path
    end

    def kill
      if @job.kill
        flash[:success] = "Job #{params[:id]} has been killed."
      else
        flash[:error] = "Could not kill job #{params[:id]}"
      end

      redirect_to resque_jobs_job_path params[:id]
    end

    def delete_all
      authorize Job

      job_ids = Job.delete_all
      if job_ids.present?
        flash[:success] = "Deleted #{job_ids.count} jobs"
      else
        flash[:error] = "No jobs available to delete"
      end

      redirect_to resque_jobs_jobs_path
    end

    def delete_completed
      authorize Job

      job_ids = Job.delete_completed
      if job_ids.present?
        flash[:success] = "Deleted #{job_ids.count} completed jobs"
      else
        flash[:error] = "No completed jobs available to delete"
      end

      redirect_to resque_jobs_jobs_path
    end

    def delete_failed
      authorize Job

      job_ids = Job.delete_failed
      if job_ids.present?
        flash[:success] = "Deleted #{job_ids.count} failed jobs"
      else
        flash[:error] = "No failed jobs available to delete"
      end

      redirect_to resque_jobs_jobs_path
    end

    protected

    def set_job
      @job = Job.find params[:id]

      if @job.blank?
        flash[:error] = "Job #{params[:id]} does not exist"
        return redirect_to(resque_jobs_jobs_path)
      end

      authorize @job
    end
  end
end
