#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2009 Markus Korn <thekorn@gmx.de>
#
# ##################################################################
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# See file /usr/share/common-licenses/GPL for more details.
#
# ##################################################################

import os
import sys
from optparse import OptionParser, make_option
from launchpadlib.uris import lookup_service_root
from ubuntutools.lp.libsupport import Launchpad, translate_api_web, LEVEL

class CmdOptions(OptionParser):

    USAGE = (
        "\t%prog create -c <consumer> [--service <staging|edge>]"
    )

    OPTIONS = (
        make_option("-c", "--consumer", action="store", type="string",
            dest="consumer", default=None),
        make_option("-s", "--service", action="store", type="string",
            dest="service", default="edge"),
        make_option("--cache", action="store", type="string",
            dest="cache", default=None),
        make_option("-o", action="store", type="string",
            dest="output", default=None),
        make_option("-l", "--level", action="store", type="int",
            dest="level", default=0,
            help="integer representing the access-level (default: 0), mapping: %s" %LEVEL),
    )

    TOOLS = {
        "create": ( ("consumer",),
                    ("service", "cache", "output",
                     "level")),
        "list": (tuple(), ("service", )),
    }

    def __init__(self):
        OptionParser.__init__(self, option_list=self.OPTIONS)
        self.set_usage(self.USAGE)

    def parse_args(self, args=None, values=None):
        options, args = OptionParser.parse_args(self, args, values)
        given_options = set(i for i, k in self.defaults.iteritems() if not getattr(options, i) == k)

        if not args:
            self.error("Please define a sub-tool you would like to use")
        if not len(args) == 1:
            self.error("Only one sub-tool allowed")
        else:
            tool = args.pop()
            if not tool in self.TOOLS:
                self.error("Unknown tool '%s'" %tool)
        needed_options = set(self.TOOLS[tool][0]) - given_options
        if needed_options:
            self.error("Please define the following options: %s" %", ".join(needed_options))
        optional_options = given_options - set(sum(self.TOOLS[tool], ()))
        if optional_options:
            self.error("The following options are not allowed for this tool: %s" %", ".join(optional_options))
        options.service = lookup_service_root(options.service)
        if options.level in LEVEL:
            options.level = LEVEL[options.level]
        elif options.level.upper() in LEVEL.values():
            options.level = options.level.upper()
        else:
            self.error("Unknown access-level '%s', level must be in %s" %(options.level, self.LEVEL))
        return tool, options

def create_credentials(options):
    launchpad = Launchpad.get_token_and_login(options.consumer,
        options.service, options.cache)
    credentials = launchpad.credentials

    if options.output:
        filepath = options.output
    else:
        credentialsDir = os.path.expanduser("~/.cache/lp_credentials")
        if not os.path.isdir(credentialsDir):
            os.makedirs(credentialsDir)
        os.chmod(credentialsDir, 0700)
        filepath = os.path.expanduser("%s/%s-%s.txt" % \
            (credentialsDir, options.consumer, str(options.level).lower()))

    f = open(filepath, "w")
    # Make credentials file non-world readable.
    os.chmod(filepath, 0600)
    credentials.save(f)
    f.close()

    print "Credentials successfully written to %s." % filepath

    return

def list_tokens(options):
    print "Not implemented yet."
    print "To get a list of your tokens, please visit %speople/+me/+oauth-tokens" %translate_api_web(options.service)
    return 1

def main():
    cmdoptions = CmdOptions()
    tool, options = cmdoptions.parse_args()
    if tool == "create":
        return create_credentials(options)
    elif tool == "list":
        return list_tokens(options)

if __name__ == "__main__":
    sys.exit(main())