module Notifications
  class Item < Notifications::Base

    attributes :id, :group_name, :message, :notification_type, :created_at
    self.primary_attribute = :id

    def self.all(options = {})
      response = get "/notifications", params: options

      notifications = response.body["notifications"].map do |notifications_attributes|
        from_attributes(notifications_attributes)
      end

      paginate notifications, total_pages: response.body["total_pages"]
    end

    def self.find(id)
      response = get "/notifications/#{id}"

      if response.success?
        from_attributes(response.body)
      else
        raise response.body["error"]
      end
    end

    def save
      response = post "/notifications", body: attributes

      self.errors.add(:base, response.body["error"]) unless response.success?

      response.success?
    end

    def destroy
      response = delete "/notifications/#{primary_attribute_value}"

      self.errors.add(:base, response.body["error"]) unless response.success?

      response.success?
    end

    def timestamp
      Time.parse(created_at) rescue nil
    end

    def preview
      self.class.markdown message
    end

    def self.markdown(text)
      response = get "/markdown", params: {text: text}
      response.body["text"]
    end
  end
end
