# 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)

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 = 'Importer 5.0: '
    result_list = sab.own_search_by_note(pattern, show_browsing_safeboxes=True)

    # result_list contains found records
    # You can get following fields:

    # note ... field note in record

    import_list = []
    for id in result_list:
        rec = sab.get_record(id)
        note = rec["note"]
        lines = note.splitlines()
        for s in lines:
            # string.find() method searches patterns case sensitive
            if s != '' and s.find(pattern) >= 0:
                if s not in import_list:
                    import_list.append(s)

                break


    import_list.sort()

    print()
    print('Import stamps:')
    print()
    for s in import_list:
        s = s.replace(pattern, '')
        print(s)


# 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

