# 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 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)
    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)
    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
    if len(sys.argv) > 2:
        login = sys.argv[1]
        password = sys.argv[2]
    console_login(login, password)
