#!/usr/bin/python

# TODO: Cleanup import statements
import os
import sys
import httplib2
import socket
import launchpadlib
from launchpadlib.launchpad import Launchpad
from lpltk import LaunchpadService
from lpltk.debug import *
read_only = True

class LaunchpadService:
    """
    TODO:
      * Document class
      * Document LPLTK_DEBUG environment option
    """

    def __init__(self, consumer='lpltk', service_root='production', read_only=False):
        """
        If launchpad cannot be accessed, will throw an exception (TODO).
        @param consumer: TODO
        @param service_root: TODO
        @param read_only: TODO
        """
        self.consumer = consumer
        self.service_root = service_root
        self.read_only = read_only

        ''' Debugging '''
        if "LPLTK_DEBUG" in os.environ:
            httplib2.debuglevel = os.getenv("LPLTK_DEBUG", None)
            sys.stdout = DebugStdOut()

        dbg("Launchpadlib Version: %s" %(launchpadlib.__version__))
        dbg("Login With:  %s %s" %(self.consumer, self.service_root))
        dbg("Read Only:  %s" %(self.read_only))

        if not self._get_creds():
            err("Error:  Could not retrieve credentials from launchpad")

    def _get_creds(self):
        if self.read_only:
            # TODO:  Only supported on 1.5.4 or newer
            self.launchpad = Launchpad.login_anonymously(self.consumer, self.service_root)
        else:
            self.launchpad = Launchpad.login_with(self.consumer, self.service_root)
        return True

# Need >= 1.5.1
if read_only:
    lp = LaunchpadService(read_only=True, service_root="edge")
    print lp.launchpad.bugs[1].title

else:
    lp = LaunchpadService(read_only=False)
    print 'Hello, %s!' % lp.launchpad.me.display_name


#lp = LaunchpadService()
#d = lp.load_project("ubuntu")

#for bugtask in d.searchTasks(assignee=lp.launchpad.me):
#    print bugtask.title
#    print "  Reported by: ",bugtask.owner.display_name
#    print "  Importance:  ",bugtask.importance
#    print "  Status:      ",bugtask.status
#    print "  Assigned on: ",bugtask.date_assigned
#    if bugtask.milestone:
#        print "  Milestone:   ",bugtask.milestone.name
#    print
