#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
stores the beeswax credentials to the keychain
"""
from __future__ import unicode_literals

import argparse
import getpass
import ujson

from beeswax_wrapper.credentials.credential_manager import store_beeswax_credentials, get_beeswax_credentials


try:
    input = raw_input
except NameError:  # 2to3
    pass


_HELP_TEXT = """Retrieves or updates the beeswax user credentials.
For either method (retrieve or update) the user will
be prompted for both a username and password
if not already provided. """


def _main():
    parser = argparse.ArgumentParser(description=_HELP_TEXT)

    subparsers = parser.add_subparsers(title='commands', help='Options for credential management', dest='command')
    subparsers.required = True  # 2to3

    retireve_parser = subparsers.add_parser('retrieve', description='Retrieve beeswax credentials.')
    retireve_parser.set_defaults(func=get_beeswax_credentials)

    update_parser = subparsers.add_parser('update', description='Update beeswax credentials.')
    update_parser.set_defaults(func=store_beeswax_credentials)

    update_parser.add_argument('--username', dest='username', help='Beeswax username')
    update_parser.add_argument('--password', dest='password', help='Beeswax password')

    args = parser.parse_args()

    if args.func is get_beeswax_credentials:
        print(ujson.dumps(args.func()))

    else:
        username = args.username or input('Beeswax Username: ')
        password = args.password or getpass.getpass('Beeswax Password: ')
        print(args.func(username, password) or 'Credentials stored successfully.')


if __name__ == '__main__':
    _main()
