module Keys
  class ReportsController < Keys::BaseController
    def index
      authorize Report

      @reports = []
      unless params[:pool_id].present?
        flash[:error] = 'Pool id is required'
        return
      end

      @pool_id = params[:pool_id]

      cursor = ''
      if params[:cursor].present?
        cursor = params[:cursor]
      end

      resp = Report.all(@pool_id, cursor, current_user.ldap_login)

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

      unless resp.body['key_pool_reports'].nil?
        @reports = resp.body['key_pool_reports']
      end
      @cursor = resp.body['cursor']
      @report = Report.new
    end

    def create
      authorize Report

      @report = Report.new
      permitted = params.require(:keys_report).permit(:pool_id).merge(ldap_login: current_user.ldap_login)
      @report.attributes = permitted

      resp = @report.generate_report
      unless resp.success? && resp.status == 200
        flash[:error] = 'Error starting report generation'
        return redirect_back
      end

      flash[:success] = 'Successfully started report generation'

      redirect_back
    end

    def download
      authorize Report

      permitted = params.permit(:report_id).merge(ldap_login: current_user.ldap_login)
      @report = Report.from_attributes(permitted)

      resp = @report.report_download_info
      unless resp.success? && resp.status == 200
        flash[:error] = 'Error downloading report'
        return redirect_back
      end

      download_url = resp.body['download_url']
      decryption_key = resp.body['decryption_key']

      decrypted_report = Report.download_and_decrypt_report(download_url, decryption_key)
      unless decrypted_report != ''
        flash[:error] = 'Error downloading report'
        return redirect_back
      end

      send_data decrypted_report,
                :filename => "key_report_#{@report.report_id}_.csv",
                :type => "text/csv"
    end

  end
end