require_relative 'category'

module Devops
  module Model
    class Environment

      include ActiveModel::Validations

      attr_accessor :id, :categories, :run_list, :expires, :users

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

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

      validates :expires, format: { with: /\A[0-9]+[smhdw]\z/, message: "Valid format is '[0-9]+[smhdw]'" }, allow_nil: true
      validates :users, usersArray: true
      validates :run_list, runListArray: true
      validates :categories, categoriesArray: true

      def get_category category
        self.categories.detect{|e| e.id == category}
      end

      def get_category!(category)
        c = get_category(category)
        raise Devops::Exception::RecordNotFound.new("Environment '#{self.id}' doesn't have category '#{category}'") unless c
        c
      end

      def initialize d
        raise InvalidRecord.new("Parameter 'id' is not a string") unless d["id"].is_a?(String)
        raise InvalidRecord.new("Parameter 'users' is not an array") unless d["users"].is_a?(Array) or d["users"].nil?
        raise InvalidRecord.new("Parameter 'run_list' is not an array") unless d["run_list"].is_a?(Array) or d["run_list"].nil?
        raise InvalidRecord.new("Parameter 'categories' is not an array") unless d["categories"].is_a?(Array) or d["categories"].nil?
        self.id = d["id"]
        self.expires = d["expires"]
        self.users = (d["users"] || []).uniq
        self.categories = (d["categories"] || []).map{|cat| Category.new(cat)}
        self.run_list = (d["run_list"] || []).uniq
      end

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

      def to_hash
        {
          "id" => self.id,
          "run_list" => self.run_list,
          "expires" => self.expires,
          "users" => self.users,
          "categories" => self.categories.map{|c| c.to_hash}
        }
      end

      def add_users users
        self.users = (self.users + users).uniq
      end

      # not reimplemented yet;
      def rename project_id, new_name
        old_name = self.id
        self.id = new_name
        self.validate_id!
        begin
          project = Devops::Db.connector.project(project_id)
          project.deploy_env(self.id)
          raise InvalidRecord.new("Environment with id '#{new_name}' already exist in project '#{project_id}'")
        rescue RecordNotFound => e
          res = create_role(project_id)
          knife = knife_instance
          old_role_name = knife.role_name(project_id, old_name)
          self.run_list.delete("role[#{old_role_name}]")
          role = res[:new] || res[:exist]
          self.run_list << "role[#{role[0]}]" unless role.nil?
          Devops::Db.connector.set_project_deploy_env_field(project_id, old_name, {"id" => new_name, "run_list" => self.run_list})
          msg = "Project '#{project_id}': environment '#{old_name}' has been renamed to '#{new_name}'." + ::Devops::Model::Project.create_roles_response(res)
          DevopsLogger.logger.info(msg)
          msg
        end
      end

      def update_field project_id, field, value
        self.send(field + "=", value)
        self.send("validate_" + field + "!")
        Devops::Db.connector.set_project_deploy_env_field(project_id, self.id, {field => value})
      end

    end
  end
end
