require 'google/apis/admin_directory_v1'
require 'google/apis/groupssettings_v1'

class GoogleAPI::CreateGoogleGroup
  DESCRIPTION = "This is a Google Group generated by Affinity.works."

  class << self
    # (Google::Apis::AdminDirectoryV1::DirectoryService String, String)
    #  => Google::Apis::AdminDirectoryV1::Group
    def call(directory_service:, group_email:, group_name:)
      create_google_group(directory_service, group_email, group_name)
    end

    private

    def create_google_group(directory_service, group_email, group_name)
      group = Google::Apis::AdminDirectoryV1::Group.new(
        email: group_email,
        name: group_name,
        description: DESCRIPTION
      )
      directory_service.insert_group(group)
    rescue  => e
      handle_error e
    end

    def handle_error(e)
      logger = Logger.new(STDOUT)
      logger.error "Uncaught #{e} exception while trying to create google group: #{e.message}"
      logger.error "Stack trace: #{e.backtrace.map {|l| print_line(l) }.join}"
      nil
    end

    # HACK!
    def print_line(l)
      "#{l}\n"
    end
  end
end
