from libzilla.promptmaker import prompt_for_credentials
from libzilla.promptmaker import prompt
from libzilla.exceptions import LibZillaException
from configparser import ConfigParser

import libzilla.validator as validator
import collections
import logging
import os

DEFAULT_RCFILE = os.path.expanduser('~/.libzillarc')
DEFAULT_TOKENFILE = os.path.expanduser('~/.libzillatoken')
DEFAULT_SECTION = 'gentoo'
KEYS_IN_RCFILE = 'url username password'.split()

logging.basicConfig(level=logging.INFO,
                    format='[%(asctime)s][%(name)s][%(levelname)s]: %(message)s')
logger = logging.getLogger(__name__)

"""The ConfigManager class reads and also helps create a ~/.libzillarc file to
find out the user's credentials in order to log into Bugzilla."""


class ConfigManager(ConfigParser):
    def __init__(self):
        super().__init__(default_section=DEFAULT_SECTION)
        self.read([DEFAULT_RCFILE])
        self.rcfile = {}

    def __str__(self):
        return '<{0} <id={1}> <rcfile={2}>>'.format(
            self.__class__.__name__,
            id(self),
            self.rcfile
        )

    def obtain_credentials(self):
        if not os.path.exists(DEFAULT_RCFILE):
            logger.info('File \"{0}\" not found! Prompt user for credentials.'.format(DEFAULT_RCFILE))
            credentials = collections.OrderedDict()
            self.rcfile = prompt_for_credentials(credentials)
            if prompt('Would you like to record these settings in {0}? [y/n] '.format(DEFAULT_RCFILE)) == 'y':
                self.save_rcfile()
            else:
                logger.info('Keeping settings in memory for the remaining of the session.')
        else:
            logger.info('File \"{0}\" found!'.format(DEFAULT_RCFILE))
            self.walk_rcfile()

        return self.rcfile

    def save_rcfile(self):
        logger.info('Storing settings in \"{0}\" ...'.format(DEFAULT_RCFILE))
        for item in self.rcfile:
            self.set(DEFAULT_SECTION, item, self.rcfile[item])

        with open(DEFAULT_RCFILE, 'w') as rcfile:
            self.write(rcfile)

        os.chmod(DEFAULT_RCFILE, 0o600)
        logger.info('Settings successfully recorded!')

    def walk_rcfile(self):
        for item in self.items(DEFAULT_SECTION):
            k, v = item
            self.rcfile[k] = v

        try:
            for key in KEYS_IN_RCFILE:
                self.rcfile[key]
        except KeyError as e:
            raise LibZillaException('Missing key in .libzillarc: \"{0}\" not found'.format(e))

        self.rcfile['url'] = validator.validate_url(self.rcfile['url'])

@@ -93,58 +93,8 @@
 mpt%0A
-from libzilla.exceptions import LibZillaException%0A
 from
@@ -421,16 +421,21 @@
 cConfig(
+%0A    
 level=lo
@@ -446,32 +446,16 @@
 g.INFO,%0A
-                
     form
@@ -591,13 +591,8 @@
 and 
-also 
 help
@@ -626,18 +626,20 @@
 le to%0Afi
-nd
+gure
  out the
@@ -1202,16 +1202,41 @@
 ntials.'
+%0A                        
 .format(
@@ -1378,77 +1378,58 @@
     
-    if prompt('Would you like to record these settings in %7B0%7D? %5By/n%5D 
+else:%0A            logger.info('File %5C%22%7B0%7D%5C%22 found!
 '.fo
@@ -1453,21 +1453,9 @@
 LE))
- == 'y':%0A    
+%0A
     
@@ -1467,20 +1467,20 @@
    self.
-save
+walk
 _rcfile(
@@ -1481,24 +1481,25 @@
 cfile()%0A
+%0A
         
     else
@@ -1494,169 +1494,199 @@
     
-    else:%0A                logger.info('Keeping settings in memory f
+return self.rcfile%0A%0A    def save_rcfile(self):%0A        if os.path.exists(DEFAULT_RCFILE): return%0A%0A        if prompt('Would you like to rec
 or
+d
  the
- remaining of the session.')%0A        else:%0A            logger.info('File %5C%22%7B0%7D%5C%22 found!'
+se settings in %7B0%7D? %5By/n%5D '%0A                  
 .for
@@ -1697,32 +1697,40 @@
 DEFAULT_RCFILE))
+ != 'y':
 %0A            sel
@@ -1730,82 +1730,103 @@
     
-self.walk_rcfile()%0A%0A        return self.rcfile%0A%0A    def save_rcfile(self):
+logger.info('Keeping settings in memory for the remaining of the session.')%0A            return%0A
 %0A   
@@ -2438,31 +2438,43 @@
     
-raise LibZillaException
+import sys%0A            logger.error
 ('Mi
@@ -2522,17 +2522,67 @@
 nd'.
-format(e)
+%0A                         format(e))%0A            sys.exit(1
 )%0A%0A 

Rework credentials retrieval.