""" Create Wallet

Creates a new Wallet on Shimmer L1 network.

Usage: python create_wallet.py <user> <password> [test]

Returns: mnemonic for new wallet.
If "test" is specified, more-verbose information is provided.

"""

#!/usr/bin/env python3

import os
import sys
import shutil
import datetime
from types import SimpleNamespace
from iota_sdk import (ClientOptions, CoinType, StrongholdSecretManager, SyncOptions, Utils, Wallet)

parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
sys.path.insert(0, parent_dir)
from config_i import config
from get_wallet_credentials_i import get_wallet_credentials


def create_wallet(args):
    # Check and exit if fewer than two parameters are provided
    if len(args) < 3:
        print("Usage: connect_wallet.py <user> <password>\nReturns: mnemonic for new wallet.", file=sys.stderr, flush=True)
        return
    # Assign parameters
    userId = args[1]
    password = args[2]

    TESTING = "test" in args
    OVERWRITE = "overwrite" in args
    # Set directory and create.
    storage_dir = os.path.join(config.wallet.path, str(userId))
    stronghold_file = os.path.join(storage_dir, str(userId)+".stronghold")
    
    # Check and exit if the stronghold file already exists
    if os.path.isfile(stronghold_file):
        if TESTING: print(f"{stronghold_file} already exists.")
        if OVERWRITE:
            print(f"{datetime.datetime.now()}: create_wallet.py | Wiping and recreating ...", file=sys.stderr)
            shutil.rmtree(storage_dir)
        else:
            print("{datetime.datetime.now()}: create_wallet.py | No overwrite specified; aborting.", file=sys.stderr)
            return

    os.makedirs(storage_dir, exist_ok=True)
    secret_manager = StrongholdSecretManager(stronghold_file, password)

    client_options = ClientOptions(nodes=[config.smr.node_url])

    print (f"\n{datetime.datetime.now()}: create_wallet.py | Creating wallet for user {userId} ...", file=sys.stderr)

    # This wallet-creation command takes a couple of seconds to complete
    wallet = Wallet(
        client_options=client_options, 
        coin_type=CoinType.SHIMMER, 
        secret_manager=secret_manager,
        storage_path=storage_dir
    )

    try:
        mnemonic = Utils.generate_mnemonic()
        # This store command take around a second to complete
        print (f"{datetime.datetime.now()}: create_wallet.py | Storing mnemonic in wallet for user {userId}...", file=sys.stderr)
        wallet.store_mnemonic(mnemonic) # Generate and store mnemonic
    except Exception as e:
        print(f"Error: {e} [Failed to either generate mnemonic or store it in the wallet.]")
        return

    #####
    # Proceeding only if MNEMONIC has been successfully created and stored in wallet.

    wallet.create_account(config.wallet.alias) # Create new account
    account = wallet.get_accounts()[0]
    account.sync(options={'syncIncomingTransactions': True})  # Ensure data is up-to-date


    print(f"{datetime.datetime.now()}: Wallet {account.addresses()[0].address} created for user {userId}.", file=sys.stderr)

    return {
        "mnemonic" : mnemonic,
        "address"  : account.addresses()[0].address
    }

#if __name__ == "__main__":
    #print (create_wallet([__file__, '333','mypassword']))
    #print (create_wallet(sys.argv))