# Copyright (C) The Arvados Authors. All rights reserved.
#
# SPDX-License-Identifier: AGPL-3.0

require 'can_be_an_owner'
require 'trashable'
require 'update_priorities'

class Group < ArvadosModel
  include HasUuid
  include KindAndEtag
  include CommonApiTemplate
  include CanBeAnOwner
  include Trashable

  # Posgresql JSONB columns should NOT be declared as serialized, Rails 5
  # already know how to properly treat them.
  attribute :properties, :jsonbHash, default: {}

  validate :ensure_filesystem_compatible_name
  validate :check_group_class
  validate :check_filter_group_filters
  validate :check_frozen_state_change_allowed
  before_create :assign_name
  after_create :after_ownership_change
  after_create :update_trash
  after_create :update_frozen

  before_update :before_ownership_change
  after_update :after_ownership_change

  after_create :add_role_manage_link

  after_update :update_trash
  after_update :update_frozen
  before_destroy :clear_permissions_trash_frozen

  api_accessible :user, extend: :common do |t|
    t.add :name
    t.add :group_class
    t.add :description
    t.add :writable_by
    t.add :delete_at
    t.add :trash_at
    t.add :is_trashed
    t.add :properties
    t.add :frozen_by_uuid
    t.add :can_write
    t.add :can_manage
  end

  def default_delete_after_trash_interval
    if self.group_class == 'role'
      ActiveSupport::Duration.build(0)
    else
      super
    end
  end

  def minimum_delete_after_trash_interval
    if self.group_class == 'role'
      ActiveSupport::Duration.build(0)
    else
      super
    end
  end

  def validate_trash_and_delete_timing
    if self.group_class == 'role' && delete_at && delete_at != trash_at
      errors.add :delete_at, "must be == trash_at for role groups"
    else
      super
    end
  end

  # check if admins are allowed to make changes to the project, e.g. it
  # isn't trashed or frozen.
  def admin_change_permitted
    !(FrozenGroup.where(uuid: self.uuid).any? || TrashedGroup.where(group_uuid: self.uuid).any?)
  end

  protected

  def self.attributes_required_columns
    super.merge(
                'can_write' => ['owner_uuid', 'uuid'],
                'can_manage' => ['owner_uuid', 'uuid'],
                'writable_by' => ['owner_uuid', 'uuid'],
                )
  end

  def ensure_filesystem_compatible_name
    # project and filter groups need filesystem-compatible names, but others
    # don't.
    super if group_class == 'project' || group_class == 'filter'
  end

  def check_group_class
    if group_class != 'project' && group_class != 'role' && group_class != 'filter'
      errors.add :group_class, "value must be one of 'project', 'role' or 'filter', was '#{group_class}'"
    end
    if group_class_changed? && !group_class_was.nil?
      errors.add :group_class, "cannot be modified after record is created"
    end
  end

  def check_filter_group_filters
    if group_class == 'filter'
      if !self.properties.key?("filters")
        errors.add :properties, "filters property missing, it must be an array of arrays, each with 3 elements"
        return
      end
      if !self.properties["filters"].is_a?(Array)
        errors.add :properties, "filters property must be an array of arrays, each with 3 elements"
        return
      end
      self.properties["filters"].each do |filter|
        if !filter.is_a?(Array)
          errors.add :properties, "filters property must be an array of arrays, each with 3 elements"
          return
        end
        if filter.length() != 3
          errors.add :properties, "filters property must be an array of arrays, each with 3 elements"
          return
        end
        if !filter[0].include?(".") and filter[0].downcase != "uuid"
          errors.add :properties, "filter attribute must be 'uuid' or contain a dot (e.g. groups.name)"
          return
        end
        if (filter[0].downcase != "uuid" and filter[1].downcase == "is_a")
          errors.add :properties, "when filter operator is 'is_a', attribute must be 'uuid'"
          return
        end
        if ! ["=","<","<=",">",">=","!=","like","ilike","in","not in","is_a","exists","contains"].include?(filter[1].downcase)
          errors.add :properties, "filter operator is not valid (must be =,<,<=,>,>=,!=,like,ilike,in,not in,is_a,exists,contains)"
          return
        end
      end
    end
  end

  def check_frozen_state_change_allowed
    if frozen_by_uuid == ""
      self.frozen_by_uuid = nil
    end
    if frozen_by_uuid_changed? || (new_record? && frozen_by_uuid)
      if group_class != "project"
        errors.add(:frozen_by_uuid, "cannot be modified on a non-project group")
        return
      end
      if frozen_by_uuid_was && Rails.configuration.API.UnfreezeProjectRequiresAdmin && !current_user.is_admin
        errors.add(:frozen_by_uuid, "can only be changed by an admin user, once set")
        return
      end
      if frozen_by_uuid && frozen_by_uuid != current_user.uuid
        errors.add(:frozen_by_uuid, "can only be set to the current user's UUID")
        return
      end
      if !new_record? && !current_user.can?(manage: uuid)
        raise PermissionDeniedError
      end
      if trash_at || delete_at || (!new_record? && TrashedGroup.where(group_uuid: uuid).any?)
        errors.add(:frozen_by_uuid, "cannot be set on a trashed project")
      end
      if frozen_by_uuid_was.nil?
        if Rails.configuration.API.FreezeProjectRequiresDescription && !attribute_present?(:description)
          errors.add(:frozen_by_uuid, "can only be set if description is non-empty")
        end
        Rails.configuration.API.FreezeProjectRequiresProperties.andand.each do |key, _|
          key = key.to_s
          if !properties[key] || properties[key] == ""
            errors.add(:frozen_by_uuid, "can only be set if properties[#{key}] value is non-empty")
          end
        end
      end
    end
  end

  def update_trash
    return unless saved_change_to_trash_at? || saved_change_to_owner_uuid?

    # The group was added or removed from the trash.
    #
    # Strategy:
    #   Compute project subtree, propagating trash_at to subprojects
    #   Ensure none of the newly trashed descendants were frozen (if so, bail out)
    #   Remove groups that don't belong from trash
    #   Add/update groups that do belong in the trash

    frozen_descendants = ActiveRecord::Base.connection.exec_query(%{
with temptable as (select * from project_subtree_with_trash_at($1, LEAST($2, $3)::timestamp))
      select uuid from frozen_groups, temptable where uuid = target_uuid
},
      "Group.update_trash.select",
      [self.uuid,
       TrashedGroup.find_by_group_uuid(self.owner_uuid).andand.trash_at,
       self.trash_at])

    if frozen_descendants.any?
      raise ArgumentError.new("cannot trash project containing frozen project #{frozen_descendants[0]["uuid"]}")
    end

    if self.trash_at and self.group_class == 'role'
      # if this is a role group that is now in the trash, it loses all
      # of its outgoing permissions.
      Link.where(link_class: 'permission', tail_uuid: self.uuid).destroy_all
    end

    ActiveRecord::Base.connection.exec_query(%{
with temptable as (select * from project_subtree_with_trash_at($1, LEAST($2, $3)::timestamp)),

delete_rows as (delete from trashed_groups where group_uuid in (select target_uuid from temptable where trash_at is NULL)),

insert_rows as (insert into trashed_groups (group_uuid, trash_at)
  select target_uuid as group_uuid, trash_at from temptable where trash_at is not NULL
  on conflict (group_uuid) do update set trash_at=EXCLUDED.trash_at)

select container_uuid from container_requests where
  owner_uuid in (select target_uuid from temptable) and
  requesting_container_uuid is NULL and state = 'Committed' and container_uuid is not NULL
},
      "Group.update_trash.select",
      [self.uuid,
       TrashedGroup.find_by_group_uuid(self.owner_uuid).andand.trash_at,
       self.trash_at]).each do |container_uuid|
      update_priorities container_uuid["container_uuid"]
    end
  end

  def update_frozen
    return unless saved_change_to_frozen_by_uuid? || saved_change_to_owner_uuid?

    if frozen_by_uuid
      rows = ActiveRecord::Base.connection.exec_query(%{
with temptable as (select * from project_subtree_with_is_frozen($1,$2))

select cr.uuid, cr.state from container_requests cr, temptable frozen
  where cr.owner_uuid = frozen.uuid and frozen.is_frozen
  and cr.state not in ($3, $4) limit 1
},
                                                      "Group.update_frozen.check_container_requests",
                                                      [self.uuid,
                                                       !self.frozen_by_uuid.nil?,
                                                       ContainerRequest::Uncommitted,
                                                       ContainerRequest::Final])
      if rows.any?
        raise ArgumentError.new("cannot freeze project containing container request #{rows.first['uuid']} with state = #{rows.first['state']}")
      end
    end

ActiveRecord::Base.connection.exec_query(%{
with temptable as (select * from project_subtree_with_is_frozen($1,$2)),

delete_rows as (delete from frozen_groups where uuid in (select uuid from temptable where not is_frozen))

insert into frozen_groups (uuid) select uuid from temptable where is_frozen on conflict do nothing
}, "Group.update_frozen.update",
                                         [self.uuid,
                                          !self.frozen_by_uuid.nil?])

  end

  def before_ownership_change
    if owner_uuid_changed? and !self.owner_uuid_was.nil?
      ComputedPermission.where(user_uuid: owner_uuid_was, target_uuid: uuid).delete_all
      update_permissions self.owner_uuid_was, self.uuid, REVOKE_PERM
    end
  end

  def after_ownership_change
    if saved_change_to_owner_uuid?
      update_permissions self.owner_uuid, self.uuid, CAN_MANAGE_PERM
    end
  end

  def clear_permissions_trash_frozen
    Link.where(link_class: 'permission', tail_uuid: self.uuid).destroy_all
    ComputedPermission.where(target_uuid: uuid).delete_all
    ActiveRecord::Base.connection.exec_delete(
      "delete from trashed_groups where group_uuid=$1",
      "Group.clear_permissions_trash_frozen",
      [self.uuid])
    ActiveRecord::Base.connection.exec_delete(
      "delete from frozen_groups where uuid=$1",
      "Group.clear_permissions_trash_frozen",
      [self.uuid])
  end

  def assign_name
    if self.new_record? and (self.name.nil? or self.name.empty?)
      self.name = self.uuid
    end
    true
  end

  def ensure_owner_uuid_is_permitted
    if group_class == "role"
      @requested_manager_uuid = nil
      if new_record?
        @requested_manager_uuid = owner_uuid
        self.owner_uuid = system_user_uuid
        return true
      end
      if self.owner_uuid != system_user_uuid
        raise "Owner uuid for role must be system user"
      end
      raise PermissionDeniedError.new("role group cannot be modified without can_manage permission") unless current_user.can?(manage: uuid)
      true
    else
      super
    end
  end

  def add_role_manage_link
    if group_class == "role" && @requested_manager_uuid
      act_as_system_user do
       Link.create!(tail_uuid: @requested_manager_uuid,
                    head_uuid: self.uuid,
                    link_class: "permission",
                    name: "can_manage")
      end
    end
  end

  def permission_to_create
    if !super
      return false
    elsif group_class == "role" &&
       !Rails.configuration.Users.CanCreateRoleGroups &&
       !current_user.andand.is_admin
      raise PermissionDeniedError.new("this cluster does not allow users to create role groups")
    else
      return true
    end
  end

  def permission_to_update
    if !super
      return false
    elsif frozen_by_uuid && frozen_by_uuid_was
      errors.add :uuid, "#{uuid} is frozen and cannot be modified"
      return false
    else
      return true
    end
  end

  def self.full_text_searchable_columns
    super - ["frozen_by_uuid"]
  end
end
