# The example shows how to find a record by text pattern in record note in SecureAnyBox and update note of found record
#   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)
# get_record(self, id)
# update_record_simply(self, record_fields)

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
    # note ... record note

    print()
    print('pattern found in', len(result_list), 'records')
    print()

    updated_records = 0
    for id in result_list:
        record = sab.get_record(id)
        name = record['name']
        note = record['note']
        lines = note.splitlines()

        found = False
        new_note = ''
        for s in lines:
            # string.find() method searches patterns case sensitive
            if s == '' or s.find(pattern) == -1:
                new_note = new_note + s + '\n'
            else:
                found = True


        if found:

            record['note'] = new_note

            print('pattern found in record id=', id)
            print('                      name=', '"'+name+'"')

            if sab.update_record_simply(record):
                updated_records += 1
                print('    record UPDATED')


    print()
    print('updated records: ', updated_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

