import json
import os.path
import logging
import argparse
try:
    import instagram_private_api as app_api
except ImportError:
    import sys
    sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
    import instagram_private_api as app_api


def onlogin_callback(api, new_settings_file):
    cache_settings = api.settings
    with open(new_settings_file, 'w') as outfile:
        json.dump(cache_settings, outfile, indent=2)
        print('SAVED: %s' % new_settings_file)


if __name__ == '__main__':

    logging.basicConfig()
    logger = logging.getLogger('instagram_private_api')
    logger.setLevel(logging.WARNING)

    # Example command:
    # python examples/savesettings_logincallback.py -u "yyy" -p "zzz" -settings "test_credentials.json"
    parser = argparse.ArgumentParser(description='Pagination demo')
    parser.add_argument('-settings', '--settings', dest='settings_file_path', type=str, required=True)
    parser.add_argument('-u', '--username', dest='username', type=str, required=True)
    parser.add_argument('-p', '--password', dest='password', type=str, required=True)
    parser.add_argument('-debug', '--debug', action='store_true')

    args = parser.parse_args()
    if args.debug:
        logger.setLevel(logging.DEBUG)

    print('Client version: %s' % app_api.__version__)

    try:

        settings_file = args.settings_file_path
        if not os.path.isfile(settings_file):
            # settings file does not exist
            print('Unable to find file: %s' % settings_file)

            # login new
            api = app_api.Client(
                args.username, args.password,
                on_login=lambda x: onlogin_callback(x, args.settings_file_path))
        else:
            with open(settings_file) as file_data:
                cached_settings = json.load(file_data)
            print('Reusing settings: %s' % settings_file)

            # reuse auth settings
            api = app_api.Client(
                args.username, args.password,
                settings=cached_settings)

    except app_api.ClientCookieExpiredError as e:
        print('ClientCookieExpiredError: %s' % e)

        # Login expired
        # Do relogin but use default ua, keys and such
        api = app_api.Client(
            args.username, args.password,
            on_login=lambda x: onlogin_callback(x, args.settings_file_path))

    except app_api.ClientLoginError as e:
        print('ClientLoginError %s' % e)
        exit(9)
    except app_api.ClientError as e:
        print('ClientError %s (Code: %d, Response: %s)' % (e.msg, e.code, e.error_response))
        exit(9)
    except Exception as e:
        print('Unexpected Exception: %s' % e)
        exit(99)

    # Call the api
    user_id = '2958144170'
    followers = []
    results = api.user_followers(user_id)
    followers.extend(results.get('users', []))

    next_max_id = results.get('next_max_id')
    while next_max_id:
        results = api.user_followers(user_id, max_id=next_max_id)
        followers.extend(results.get('users', []))
        if len(followers) >= 600:       # get only first 600 or so
            break
        next_max_id = results.get('next_max_id')

    followers.sort(key=lambda x: x['pk'])
    # print list of user IDs
    print(json.dumps([u['pk'] for u in followers], indent=2))

@@ -252,240 +252,8 @@
 i%0A%0A%0A
-def onlogin_callback(api, new_settings_file):%0A    cache_settings = api.settings%0A    with open(new_settings_file, 'w') as outfile:%0A        json.dump(cache_settings, outfile, indent=2)%0A        print('SAVED: %25s' %25 new_settings_file)%0A%0A%0A
 if _
@@ -595,111 +595,8 @@
 o')%0A
-    parser.add_argument('-settings', '--settings', dest='settings_file_path', type=str, required=True)%0A
     
@@ -978,250 +978,8 @@
 __)%0A
-%0A    try:%0A%0A        settings_file = args.settings_file_path%0A        if not os.path.isfile(settings_file):%0A            # settings file does not exist%0A            print('Unable to find file: %25s' %25 settings_file)%0A%0A            # login new%0A        
     
@@ -999,33 +999,16 @@
 .Client(
-%0A                
 args.use
@@ -1031,1111 +1031,10 @@
 word
-,%0A                on_login=lambda x: onlogin_callback(x, args.settings_file_path))%0A        else:%0A            with open(settings_file) as file_data:%0A                cached_settings = json.load(file_data)%0A            print('Reusing settings: %25s' %25 settings_file)%0A%0A            # reuse auth settings%0A            api = app_api.Client(%0A                args.username, args.password,%0A                settings=cached_settings)%0A%0A    except app_api.ClientCookieExpiredError as e:%0A        print('ClientCookieExpiredError: %25s' %25 e)%0A%0A        # Login expired%0A        # Do relogin but use default ua, keys and such%0A        api = app_api.Client(%0A            args.username, args.password,%0A            on_login=lambda x: onlogin_callback(x, args.settings_file_path))%0A%0A    except app_api.ClientLoginError as e:%0A        print('ClientLoginError %25s' %25 e)%0A        exit(9)%0A    except app_api.ClientError as e:%0A        print('ClientError %25s (Code: %25d, Response: %25s)' %25 (e.msg, e.code, e.error_response))%0A        exit(9)%0A    except Exception as e:%0A        print('Unexpected Exception: %25s' %25 e)%0A        exit(99)%0A%0A    # Call the api
+)%0A
 %0A   

Simplify pagination example