module Bits
  class JobsController < Bits::BaseController

    def index
      authorize Job
      @jobs = Job.all(current_user.ldap_login)

      @job = Job.new

      @campaigns = nil
      resp = Campaign.all

      unless resp.success? && resp.status == 200
        flash[:error] = 'Error loading campaigns'
        return
      end

      @campaigns = resp.body['bulk_grant_campaigns']
    end

    def create_bulk_entitle
      authorize Job

      if params[:bits_job][:annotation] == ''
        flash[:error] = 'Failed to include an annotation'
        return redirect_back
      end

      if params[:bits_job][:bits_amount].to_i <= 0
        flash[:error] = 'Failed to include a Bits amount'
        return redirect_back
      end

      @job = Job.new
      @job.attributes = get_job_attributes

      response = @job.start_bulk_entitle_job
      if response.success?
        flash[:success] = 'Successfully started job'
      else
        flash[:error] = 'Failed to start job'
      end

      redirect_back
    end

    def create_bulk_entitle_by_campaign
      authorize Job

      if params[:bits_job][:campaign_id] == ''
        flash[:error] = 'Missing campaign id'
        return redirect_back
      end

      @job = Job.new
      @job.attributes = get_job_attributes

      response = @job.start_bulk_entitle_by_campaign_job
      if response.success?
        flash[:success] = 'Successfully started job'
      else
        flash[:error] = 'Failed to start job'
      end

      redirect_back
    end

    def get_input
      authorize Job
      @job = Job.new
      response = @job.get_input(params[:creator], params[:job_id])
      render :json => response.body
    end

    def get_options
      authorize Job
      @job = Job.new
      response = @job.get_options(params[:creator], params[:job_id])
      render :json => response.body
    end

    def get_output
      authorize Job
      @job = Job.new
      response = @job.get_output(params[:creator], params[:job_id])
      send_data response.body,
                :filename => "output_files.zip",
                :type => "application/zip"
    end

    protected

    def get_job_attributes
      users = params[:bits_job][:input_users].split("\n").collect{|u| u.strip || u }.uniq

      permitted = params.require(:bits_job).merge(creator: current_user.ldap_login)

      if params[:bits_job][:by] == 'username_lookup'
        permitted = permitted.merge(user_logins: users, user_ids: nil)
      elsif params[:bits_job][:by] == 'user_id_lookup'
        permitted = permitted.merge(user_logins: nil, user_ids: users)
      end

      permitted
    end
  end
end

