#!/usr/bin/env python

import httplib, urllib
import MySQLdb
import getpass
import ConfigParser
import getpass
import optparse
import os
import pprint
import random
import signal
import string
import subprocess
import sys
import tempfile
import time
import urllib
import urllib2
class ConfigData(object):
    

    def directory_create(self, path, mode):
        '''Create a directory if it does not exist.

        Exit if it exists and is not a directory (or symlink) or unable to create it.

        Arguments
            path -- directory path
            mode -- mode to set on directory

        '''
        if os.path.exists(path):
            if os.path.isdir(path):
                try:
                    os.chmod(path, mode)
                except Exception, exc:
                    TermColor.print_error('Failed to change mode of %r. Exiting.' % (path))
                    TermColor.print_error(str(exc))
                    sys.exit(1)
            else:
                TermColor.print_error('The path %r is not a directory. Exiting.' % (path))
                sys.exit(1)
        else:
            try:
                os.makedirs(path, mode)
            except Exception, exc:
                TermColor.print_error('Failed to create %r. Exiting.' % (path))
                TermColor.print_error(str(exc))
                sys.exit(1)


def config_data_set(prefix):
    '''Update the global config data.

    Exits when unable to create configuration directories.

    Arguments
        prefix -- The install prefix

    '''
    global CONFIG_DATA
    CONFIG_DATA = ConfigData(prefix)
    print 'Installing into %r' % (CONFIG_DATA.PREFIX)

class TermColor(object):
    '''Print colored text on a neutral background to the terminal'''
    CLRS = {
        'white': '\033[37m',
        'green': '\033[92m',
        'red': '\033[91m',
        'yellow': '\033[33m',
        'bg': '\033[40m\033m'
    }

    END = '\033[0m'

    @classmethod
    def print_clr(cls, color, txt, newline=True):
        sys.stdout.write(cls.CLRS.get(color, '')
                         + cls.CLRS['bg']
                         + txt
                         + cls.END)
        if newline:
            sys.stdout.write('\n')


    @classmethod
    def print_cmd(cls, txt, newline=True):
        cls.print_clr('yellow', txt, newline)

    @classmethod
    def print_header(cls, txt, newline=True):
        cls.print_clr('white', txt, newline)

    @classmethod
    def print_ok(cls, txt, newline=True):
        cls.print_clr('green', txt, newline)

    @classmethod
    def print_error(cls, txt, newline=True):
        cls.print_clr('red', 'Error: ' + txt, newline)

    @classmethod
    def print_delay(cls, txt, newline=True):
        cls.print_clr('red', '==> ', False)
        cls.print_ok(txt, newline)
class StateTracker(object):
    '''Pseudo-state machine'''
    def __init__(self, *states):
        '''Constructor

        Arguments
        states -- ordered sequence of names or (name, phrase) pairs. if the former,
            the phrases are generated by lowercasing the names and converting underscores
            to spaces. the unmodified names become instance attributes with index values.

        '''
        self.state = 0
        self.names = []
        self.phrases = []
        for idx, state in enumerate(states):
            if isinstance(state, basestring):
                name = state
                phrase = name.lower().replace('_', ' ')
            elif isinstance(state, (tuple, list)):
                (name, phrase) = state
            else:
                raise RuntimeError('Invalid item in state sequence: %r' % (state))
            setattr(self, name, idx)
            self.names.append(name)
            self.phrases.append(phrase)

    def advance(self):
        '''Advance the internal state.

        Prints the current state afterward.

        Raises
        RuntimeError -- if the state is already at the end

        '''
        if self.state == len(self.names):
            raise RuntimeError('Unable to advance past final state')
        else:
            self.state += 1
        TermColor.print_delay(str(self))

    def assign(self, name):
        '''Explicitly set the state.

        Prints the current state afterward.

        Return
        integer -- the previous state value

        '''
        value = getattr(self, name)
        retval, self.state = self.state, value
        TermColor.print_delay(str(self))
        return retval

    def reset(self):
        '''Reset the internal state

        Prints the current state afterward.

        Return
        integer -- the previous state value

        '''
        retval, self.state = self.state, 0
        TermColor.print_delay(str(self))
        return retval

    def __str__(self):
        '''Stringify current state value'''
        return self.phrases[self.state]

    def __cmp__(self, other):
        if isinstance(other, basestring):
            value = getattr(self, other)
        else:
            value = other.state
        return cmp(self.state, value)


def get_choice(question, choices, default=None):
    '''Prompt for a response from a selection of choices.

    Return
        The selected item from choices (value, not an index)

    Raises
        ValueError -- if default is not in choices

    Arguments
        question -- the prompt
        choices -- possible answers
        default -- optional default value

    Example
        choice = get_choice('What fruit do you want?', ['apples', 'oranges'], 'apples')
        print 'choice', choice

    '''
    if default is None:
        default_idx = None
    else:
        try:
            default_idx = choices.index(default)
        except ValueError:
            raise ValueError('Default choice %r is not in choice collection' % (default))

    enum_choices = list(enumerate(choices))
    prompt = ((default_idx is not None and ('[%d]: ' % (default_idx + 1)))
              or ': ')
    while True:
        TermColor.print_header(question)
        for idx, item in enum_choices:
            TermColor.print_ok('    %d.' % ((idx + 1)), newline=False)
            print ' %s' % (item)
        input_raw = raw_input(prompt)
        if is_integer(input_raw):
            choice_idx = int(input_raw) - 1
        elif not input_raw.strip() and default_idx is not None:
            choice_idx = default_idx
        else:
            choice_idx = None

        if choice_idx is None:
            TermColor.print_error('invalid choice value: %s' % (input_raw))
        elif choice_idx < 0 or (len(choices) <= choice_idx):
            TermColor.print_error('choice out of range: %s' % (choice_idx))
        else:
            # !!! Exit loop
            break
    return choices[choice_idx]


def get_value(name, default=None, validate=None, validate_explanation=None,
              is_password=False):
    '''Prompt for and read a value from the terminal.

    Return
        string -- the read value

    Arguments
        name -- value name
        default -- [optional] default value
        validate -- [optional] callable to validate the input. Defaults to
            ensuring something was entered.
        validate_explanation -- [optional] error message if validate() fails
        is_password -- [optional] if True, do not echo the response. Defaults to False.

    '''
    prompt_default = (default and ' [%s]' % (default)) or ''
    prompt = '%s%s: ' % (name, prompt_default)
    if is_password:
        input_fn = lambda: getpass.getpass('')
    else:
        input_fn = raw_input
    validate_fn = validate or (lambda x: bool(x))
    error_msg = validate_explanation or ('Invalid Input.  Please try again.')
    while True:
        TermColor.print_header(prompt, newline=False)
        input_raw = input_fn().strip()
        input_value = input_raw or default or ''
        if validate_fn(input_value):
            # !!! Loop exit
            break
        else:
            TermColor.print_error(error_msg)
    return input_value


def is_integer(value):
    '''Determine whether value is convertible to an integer'''
    try:
        int(value)
    except (TypeError, ValueError):
        rc = False
    else:
        rc = True
    return rc


def name_generate(db_name, max_length):
    '''Generate a database user name which does not exceed a maximum length

    If the name would exceed the maximum length, the name is shortened
    and some random digits appended.

    Return
        string -- the generated name

    Raises
        RuntimeError -- if database name and maximum length values do not
            permit generation of a useful name.

    Arguments
        db_name -- database name
        max_length -- the inclusive size limit of the generated name

    '''
    PREFIX = 'dreamdash_'
    RANDOM_SUFFIX_LENGTH = 3
    MAX_REQUIRED = len(PREFIX) + RANDOM_SUFFIX_LENGTH
    if max_length < MAX_REQUIRED:
        raise RuntimeError('Unable to generate a name with fewer than %d characters (%d specified).'
                           % (MAX_REQUIRED, max_length))
    name_full = ('%s%s%s' % (PREFIX, db_name.strip(), RANDOM_SUFFIX_LENGTH * 'X'))[:max_length]
    chars = string.digits
    name = (name_full[:-RANDOM_SUFFIX_LENGTH]
            + ''.join([random.choice(chars) for i in range(RANDOM_SUFFIX_LENGTH)]))
    return name

print "Enter the login information"
LOGIN_ATTEMPT_LIMIT = 1
for _login_attempt in range(LOGIN_ATTEMPT_LIMIT):
        TermColor.print_header('Enter your Dreamdash login information:')
        email = get_value('e-mail',
                          validate = lambda x: 0 < x.find('@'),
                          validate_explanation = 'This is not a valid email')
        password = get_value('password', is_password=True)
        # Login user
        postdata = urllib.urlencode({'email':email,'password':password})
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
conn = httplib.HTTPConnection("two.dreamdash.loc")
conn.request("POST", "/users/sign_in", postdata, headers)
response = conn.getresponse()
print response.status, response.reason 


print "Enter the db name"
db=raw_input("DB Name")

print "Enter Read_only role name"

role_name=raw_input("Role Name")

print "Enter Read_only role password"

role_password=getpass.getpass()
postdata_second={}
postdata_second["db"]=db
postdata_second["role_name"]=role_name
postdata_second["role_password"]=role_password
db = MySQLdb.connect("localhost","root","root","dreamdash1" )
cursor = db.cursor()
cursor.execute("select * from users")
for row in cursor.fetchall() :
	print row[1]
params = urllib.urlencode(postdata_second)
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
conn1 = httplib.HTTPConnection("two.dreamdash.loc")
conn1.request("POST", "/department/6/dash/my-dashboard--2", params, headers)
response = conn1.getresponse()
print response.status, response.reason 
data = response.read()
data

conn.close()