module Devops
  module Helpers
    class ResultObject
      attr_reader :code, :reason

      def initialize(code)
        @code = code
        @reason = self.class.result_codes.key(@code) || :unknown_error
      end

      def ok?
        @code == 0
      end

      def failed?
        !ok?
      end

      class << self
        def result_codes
          @result_codes || {ok: 0}
        end

        def code_of_reason(reason)
          result_codes.fetch(reason)
        end

        def from_reason(reason)
          new(code_of_reason(reason))
        end

        private

        # defines methods like :bootstrap_error?
        def set_result_codes(new_result_codes)
          @result_codes = new_result_codes
          @result_codes.each do |pretendent_reason, pretendent_code|
            define_method "#{pretendent_reason}?" do
              code == pretendent_code
            end
          end
        end
      end


    end
  end
end