require 'mongoid'
require 'set'
require "db/mongo/models/model_with_provider"

module Devops
  module Model
    class Filter

      include ::Mongoid::Document
      include ::Mongoid::Timestamps::Created
      include ::ActiveModel::Validations

      store_in collection: "filters"

      include ModelWithProvider

      field :_id, as: :'id', overwrite: true, type: String #BSON::ObjectId
      field :type, type: String
      field :images, type: Array

      def self.available_images provider
        Filter.find_by(type: "image", provider: provider).images
      rescue Mongoid::Errors::DocumentNotFound
        return []
      end

      def self.add_available_images images, provider
        return unless images.is_a?(Array)
        q = {type: "image", provider: provider}
        f = Filter.find_by(q)
        set = Set.new(f.images)
        set.merge(images)
        # do not work
        # f.add_to_set(images: images)
        Filter.collection.update_one(q, {"$addToSet" => {"images" => {"$each" => images}}})
        set.to_a
      rescue Mongoid::Errors::DocumentNotFound
        Filter.create('type' => 'image', 'provider' => provider, 'images' => images)
        return images
      end

      def self.delete_available_images images, provider
        return unless images.is_a?(Array)
        q = {type: "image", provider: provider}
        filter = Filter.find_by(q)
        Filter.collection.update_one(q, {"$pullAll" => {images: images}})
        filter.images - images
      rescue Mongoid::Errors::DocumentNotFound
        []
      end

    end
  end
end
