require_relative 'element'

module ExternalMemory

  class ApiElement < Sequel::Model
    include ExternalMemory::ExtendedElement
    plugin :validation_helpers
    many_to_one :element

    def validate
      super
      validates_presence([:element_id])
    end

    def to_json(params = {})
      result = element_to_json(params).merge(
          {
              :custom_ids => (custom_ids || []),
              :tags => (tags || []),
              :authors => (authors || []),
          })
      if description
        result[:description] = description
      end
      result
    end

    dataset_module ExternalMemory::ExtendedElementModule
    dataset_module do

      # Order by created_at
      def order_by_created_at
        order(Sequel.lit('element.created_at desc'))
      end

      # Filter api elements by its custom ids
      def by_source_id_and_custom_id(source_id, custom_id)
        where(:element => ExternalMemory::Element.where(:source_id => source_id)).where(Sequel.pg_array_op(:custom_ids).contains([custom_id]))
      end

      def by_source_id_and_element_id(source_id, element_id)
        where(:element => ExternalMemory::Element.where(:source_id => source_id, :id => element_id)).first
      end

    end


    MODEL_INFO = {
        :id => {
            :type => Integer,
            :description => 'The unique id',
            :example => 42,
        },
        :custom_id => {
            :type => String,
            :description => 'A custom id for the source',
            :example => '31db504e-ea71-48f6-b6e7-aec115352c22',
        },
        :custom_ids => {
            :type => [String],
            :description => 'A list of custom id for the source',
            :example => ['31db504e-ea71-48f6-b6e7-aec115352c22'],
        },
        :urls => {
            :type => [String],
            :description => 'A list of urls',
            :example => ['http://google.com'],
        },
        :description => {
            :type => String,
            :description => 'The element\'s description',
        },
        :authors => {
            :type => [String],
            :description => 'The authors',
        },
        :tags => {
            :type => [String],
            :description => 'The tags',
        },
        :timestamp => {
          :type => DateTime,
          :description => 'The element timestamp',
        },
    }

  end

end
