require 'mongoid'
require "db/mongo/models/model_with_provider_account"

module Devops
  module Model
    class Image

      include ::Mongoid::Document
      include ::Mongoid::Timestamps::CreatedInt
      include ::ActiveModel::Validations

      include ModelWithProviderAccount
      store_in collection: "images"

      field :image_id, type: String
      field :remote_user, type: String
      field :name, type: String

      MAX_ID_LEN = 100
      NAME_REGEX = /\A[\w_\-\.]{1,#{MAX_ID_LEN}}\z/

      field :_id, as: :'id', overwrite: true, type: String, default: ->{ "#{self.image_id}_#{self.provider}_#{self.provider_account}" }

      validates_uniqueness_of :id, message: "image already exists", on: :create

      validates_presence_of :image_id, message: "'image_id' is undefined"
      validates_length_of :image_id, minimum: 1, maximum: MAX_ID_LEN
      validates_format_of :image_id, with: NAME_REGEX, message: "invalid image_id, it should contains 'a-zA-Z0-9-._' symbols"

      validates_presence_of :remote_user, message: "'remote_user' is undefined"
      validates_length_of :remote_user, maximum: 31
      validates_format_of :remote_user, with: /\A[a-z_][a-zA-Z0-9_-]{0,30}\z/, message: "invalid remote_user"

      validates_presence_of :name, message: "'name' is undefined"
      validates_length_of :name, maximum: 255

      validate :validate_params

      def validate_params
        validate_provider
        return unless errors.empty?
        aimages = Devops::Model::Filter.available_images(self.provider)
        if aimages.include?(self.image_id)
          provider_images = self.provider_instance.images([self.image_id])
          errors.add(:id, 'Can not find image in provider database') if provider_images.empty?
        else
          errors.add(:id, 'Invalid id, please check images filter')
        end
      end

      def validate!
        raise Devops::Exception::ValidationError.create_from_messages(self.errors.messages) unless self.valid?
      end

      def initialize hash
        check_provider_account_type(hash)
        raise Devops::Exception::ParserError.new("Parameter 'image_id' is not a string") unless hash["image_id"].is_a?(String)
        raise Devops::Exception::ParserError.new("Parameter 'remote_user' is not a string") unless hash["remote_user"].is_a?(String)
        raise Devops::Exception::ParserError.new("Parameter 'name' is not a string") unless hash["name"].is_a?(String)
        super(hash)
      end

      def to_hash
        hash = self.attributes.clone
        hash["id"] = hash.delete("_id")
        hash["created_at"] = hash.delete("created_at").to_i if hash["created_at"]
        hash
      end

      def to_hash_update
        hash = self.attributes.clone
        hash.delete("_id")
        hash.delete("created_at") if hash["created_at"]
        hash
      end

    end
  end
end
