module Shared::Errors
  # Note: This module is NOT a concern

  class ProcessError < StandardError
    def initialize(msg, status = 404)
      if msg.kind_of?(Hash)
        opts = msg.symbolize_keys
        @status = opts[:status]
        super(opts[:message])
      else
        @status = status
        super(msg)
      end
    end
    attr_accessor :status
  end

  private
  def raise_error_400(msg = "")
    raise ProcessError.new(msg, 400)
  end

  def raise_error_403(msg = "")
    raise ProcessError.new(msg, 403)
  end

  def raise_error_404(msg = "")
    raise ProcessError.new(msg, 404)
  end

  def render_error(opt)
    @message = opt[:message]
    opt[:status] ||= 400
    opt[:template] ||= "misc/error_#{opt[:status]}"
    respond_to do |format|
      format.html { render opt }
      format.json {
        opt.delete :template
        render :json => opt, :status => opt[:status]
      }
    end
  end

  def render_proc_error(e)
    _log :error, "Process error [#{request.path}]: (#{e.status}) #{e.message}"
    render_error message: e.message, status: e.status
  end

  def render_res_error(e)
    _log :error, "NotFound [#{request.path}]: (404) #{e.message}"
    render_error message: e.message, status: 404
  end

  def render_cancan_error(e)
    _log :error, "AccessDenied [#{request.path}]: (#{current_user.try(:username)}, id=#{current_user.try(:id).inspect}) #{e.message}"

    render_error :message => e.message, :status => 403
  end
end
