# The example shows how to find a record by text pattern in record note in SecureAnyBox and delete it
#   in this example, helper method own_search_by_note is used to get found id of objects

# SABClient methods used:
#
# login(self, username, password, domain='system', access_code=None)
# logout(self)
# own_search_by_note(self, pattern, show_browsing_safeboxes)
# delete_record(self, id)

import sys
import json
import sabclient

# If the logged-on user requests a second factor, SABClient calls the second factor callback 
#   to retrieve the six-digit code
def get_second_factor():
  print('** SECOND FACTOR AUTHENTICATION **')
  print()
  s = input("Enter 6-digit code from your authenticator application: ") 
  return s

################################## main ######################################################

# first we need to create SecureAnyBox (SAB) client for given SAB server address (including base path);
# the callback applies when the second factor is required to sign in
sab = sabclient.SABClient('http://127.0.0.1:8843/secureanybox/', callback=get_second_factor)

# Then we need to authenticate the user.
# Don't use admin account, create account with minimum access rights, only to the required safe box
result = sab.login('serviceuser', 'password', domain='test')

if result:

    # method SABClient.search_by_note can search stored records (such as Accounts, File, etc.), 
    # by pattern in their note

    pattern = 'Imported 2020 Sep 01'
    result_list = sab.own_search_by_note(pattern, show_browsing_safeboxes=True)

    # result_list contains found records
    # You can get following fields:

    # id ... ID of Record
    # name ... Record name

    print()
    print('pattern found in', len(result_list), 'records')
    print()

    deleted_records = 0
    for id in result_list:
        record = sab.get_record(id)
        name = record['name']

        print('pattern found in record id=', id)
        print('                      name=', '"'+name+'"')

        if sab.delete_record(id):
            print('    record DELETED')
            deleted_records += 1


    print()
    print('deleted records: ', deleted_records)

# when not needed anymore, you can logout the client, which will destroy session cookies and the client can no
# longer be used to work with SAB server
sab.logout

