from onepassword_tools.lib.OnePasswordUtils import OnePasswordUtils
from onepassword_local_search.OnePassword import OnePassword
from onepassword_tools.lib.MiscUtils import generate_password
from onepassword_tools.lib.MiscUtils import SimpleFormatter
from onepassword_tools.lib.OnePasswordLoginItem import OnePasswordLoginItem
from onepassword_tools.lib.OnePasswordResult import OnePasswordResult
from onepassword_tools.lib.ClickUtils import ClickUtils
import click
import copy
import json
import sys


@click.command()
@click.option('--url', help='URL of the website where the account is created', prompt=True, required=True)
@click.option('--username', help='Account username', prompt=True, required=True)
@click.option('--password', help='Password to use, default autogenerated')
@click.option('--password-length', help='Autogenerated password length, default 25', default=25, type=int)
@click.option('--title', help='Name of the 1Password item', default='', prompt=True, required=False)
@click.option('--return-field', required=False, help='Field value to return', default=None)
@click.option('--vault', required=False, help='Vault uuid where to store the information')
@click.option('--account', required=False, help='Account to use (shorthand)')
def new_website_account(url, title, username, password, password_length, return_field, vault, account):
    """Create a new Login item in 1Password with the given credentials."""
    NewWebsiteAccount(**locals()).run()


class NewWebsiteAccount:

    account: str = None
    entryTitleTemplate = 'ACCOUNT %s ON %s'
    url: str = None
    onePassword: OnePassword
    onePasswordUtils: OnePasswordUtils
    password: str = None
    password_length: int = 25
    return_field: str = None
    title: str = None
    username: str = None
    vault: str = None

    def __init__(self, **kwargs):
        self.onePasswordUtils = OnePasswordUtils()
        self.onePassword = OnePassword()
        self._init(**kwargs)
        if self.password is None:
            self.password = generate_password(self.password_length)


    def _init(self, **kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)

    def run(self):

        if not self.onePasswordUtils.is_authenticated():
            self.onePasswordUtils.authenticate()

        item = self.save_on_1password()
        if 'uuid' in item.keys():
            result = ''
            if self.return_field is None:
                print(json.dumps(item))
            else:
                if self.return_field in item.keys():
                    result = item[self.return_field]
                else:
                    result = OnePasswordResult(dict(details=item['request_object'])).get(self.return_field)
            print(result)
            sys.exit(0)
        else:
            ClickUtils.error('Unable to save entry in 1Password')
            sys.exit(1)

    def save_on_1password(self):
        arguments = vars(copy.copy(self))
        del arguments['onePassword']
        del arguments['onePasswordUtils']
        login_item = OnePasswordLoginItem(**arguments)
        request_object = login_item.get_request_object()
        return self.onePasswordUtils.create_item(
            account=self.account,
            request_object=request_object,
            template=login_item.item_type,
            title=self.get_title(login_item),
            vault=self.vault,
            url=self.url
        )

    def get_title(self, item):
        if self.title is None or self.title == '':
            return self.entryTitleTemplate % (self.username, self.url)
        sf = SimpleFormatter()
        return sf.format(self.title, item).strip()

