require "json"

module Devops
  module Model
    class Key

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

      store_in collection: "keys"

      field :_id, as: :'id', overwrite: true, type: String
      field :path, type: String

#      validates_presence_of :id, message: "'id' is undefined"
      validates_length_of :id, maximum: 100
      validates_format_of :id, with: /\A[a-z_][a-z0-9_-]{0,99}\z/, message: "invalid id"

      before_destroy :delete_file

      def initialize hash
        raise InvalidRecord.new("Parameter 'id' is not a string") unless hash["id"].is_a?(String)
        super(hash)
      end

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

      def filename
        File.basename(self.path)
      end

      def to_list_hash
        {
          "id" => self.id,
          "filename" => self.filename,
          "created_at" => self.created_at
        }
      end

      private
      def delete_file
        FileUtils.rm(self.path)
        DevopsLogger.logger.info("File '#{self.path}' has been removed")
      rescue
        DevopsLogger.logger.error "Missing key file for #{key_id} - #{k.filename}"
      end

    end
  end
end
