# Copyright 3D Control Systems, Inc. All Rights Reserved 2017-2019.
# Built in San Francisco.

# This software is distributed under a commercial license for personal,
# educational, corporate or any other use.
# The software as a whole or any parts of it is prohibited for distribution or
# use without obtaining a license from 3D Control Systems, Inc.

# All software licenses are subject to the 3DPrinterOS terms of use
# (available at https://www.3dprinteros.com/terms-and-conditions/),
# and privacy policy (available at https://www.3dprinteros.com/privacy-policy/)

import os
import sys
import hashlib
import logging

import user_login


class DummyApp:

    def __init__(self):
        self.offline_mode = False
        self.stop_flag = False
        self.logger = logging.getLogger()

    def register_error(self, *args, **kwargs):
        print(args)
        print(kwargs)


dummy_app = DummyApp()


def console_login(login, password):
    if not login:
        login = input('Your 3DPrinterOS account email: ')
    if not password:
        from getpass import getpass
        password = getpass('Your 3DPrinterOS password: ')
    login_manager = user_login.UserLogin(parent=dummy_app, auto_login=False)
    password = hashlib.sha256(password.encode("utf-8")).hexdigest()
    if "-o" in sys.argv:
        print('Warning - offline mode. Saving login credentials without checking them.')
        login_manager.save_login(login, password)
    elif "-d" in sys.argv:
        print('Warning: dump mode. Login credentials file would be saved into stuff.bin file in the current working folder')
        login_manager.save_login(login, password, os.path.curdir)
    elif "-t" in sys.argv:
        print('Warning: test only mode. Nothing will be saved or changed')
    elif "-e" in sys.argv:
        print('Warning: erasing login!')
        sys.exit(0)
    else:
        error = login_manager.login_as_user(login, password)
        if error:
            print('Login failed! ' + str(error))
            sys.exit(1)
    print('Login successful: ' + login)


if __name__ == '__main__':
    login, password = None, None
    for arg in sys.argv[1:]:
        if not arg.startswith('-'):
            if not login:
                login = arg
                print("Login:", login)
            else:
                password = arg
                print("Password:", password)
    console_login(login, password)
