require "db/mongo/models/user"
require "app/api3/parsers/user"
require_relative "request_handler"

module Devops
  module API3
    module Handler
      class User < RequestHandler

        set_parser Devops::API3::Parser::UserParser

        def users
          Devops::Model::User.all
        end

        def create
          Devops::Model::User.create! parser.create
        end

        def get_user id
          Devops::Model::User.find(id)
        rescue Mongoid::Errors::DocumentNotFound
          raise Devops::Exception::RecordNotFound.new("User with id '#{id}' not found")
        end

        def delete user_id
          user = get_user(user_id)
          projects = Devops::Model::Project.find({'environments.users' => user_id})
          str = ""
          projects.each do |p|
            p.environments.each do |e|
              str+="#{p.id}.#{e.id} " if e.users.include? user_id
            end
          end
          raise Devops::Exception::ConflictError.new "Deleting is forbidden: User is included in #{str}"
        rescue Mongoid::Errors::DocumentNotFound
          user.delete
        end

        def add_roles id
          user = get_user(id)
          user.add_to_set({roles: parser.roles})
        end

        def delete_roles id
          user = get_user(id)
          user.pull_all({roles: parser.roles})
        end

        def change user_id, action
          user = get_user(user_id)
          user.send action + "=", parser.change(action)
          user.save!
        end

        def update_user id
          user = get_user(id)
          obj = parser.update_user
          %w(email password roles).each do |key|
            user.send(key + "=", obj[key]) if obj.key?(key)
          end
          user.save!
        end
      end
    end
  end
end

