def __init__(self, elementId, db):
     print "start"
     self.element_id = elementId
     self.proyectos_db = db
     self.conector_db = ConectorSqlite()
     self.tablas_db = TablasSqlite()
 def __init__(self, elementId, db):
     print "start"
     self.element_id = elementId
     self.proyectos_db = db
     self.conector_db = ConectorSqlite()
     self.tablas_db = TablasSqlite()
class ProyectoTerminal(object):
    
    def __init__(self, elementId, db):
        print "start"
        self.element_id = elementId
        self.proyectos_db = db
        self.conector_db = ConectorSqlite()
        self.tablas_db = TablasSqlite()
    
    def return_false(self):
        return False
                    
    def new_connection(self):
        print "========== Create a new connection ================"
        aux = Conector()
        aux.proyecto_id = self.element_id
        aux.tipo = 1
        
        has_error = True
        host = ""
        while has_error:
            host = raw_input("[Host] > ")
            if host != "":
                has_error = False
        aux.host = host
        
        has_error = True
        port = ""
        while has_error:
            port = raw_input("[Port] > ")
            if port != "":
                has_error = False
        aux.port = port
        
        has_error = True
        user = ""
        while has_error:
            user = raw_input("[User] > ")
            if user != "":
                has_error = False
        aux.user = user
        
        has_error = True
        password = ""
        while has_error:
            password = raw_input("[Password] > ")
            if password != "":
                has_error = False
        aux.password = password
        
        
        schema = ""
        schema = raw_input("[Schema] > ")
        aux.schema = schema
        
        has_error = True
        master = 0
        while has_error:
            try:
                aux_master = raw_input("[Master] > ")
                master = int(aux_master)
                if master == 0 or master == 1:
                    has_error = False
            except ValueError:
                print "It has to be a number" 
        aux.master = master
        
        aux.id = self.conector_db.insert_element(aux)
        return True

    def edit_table(self, tableId):
        aux = self.tablas_db.findOne(tableId)
        print "============== Editing table =================="
        print aux
        print "============ Choose options ==================="
        
        has_error = True
        use_all = 0
        while has_error:
            try:
                aux_master = raw_input("[Use all (1 for All and 0 for None)] > ")
                use_all = int(aux_master)
                if use_all == 0 or use_all == 1:
                    has_error = False
            except ValueError:
                print "It has to be a number" 
        aux.use_all = use_all
        
        
        condition = ""
        condition = raw_input("[Condition] > ")
        if condition != "":
            aux.condition = condition
        
        self.tablas_db.update_element(aux)
        
        print "Dont doing anything..."

    def populate_tables(self):
        stealLogic = StealerLogic()
        stealLogic.populate_tables(self.element_id)
        return True

    def edit_conector(self, conectorId):
        
        print "Dont doing anything..."
                
    def list_tables(self, limit = setup_options.getLimit(), page = 1):
        print "============= Listing tables =================="
        quantity_tables = self.tablas_db.retrieveAllCount(self.element_id)
        number = 1
        while number != 0:
            tablas = self.tablas_db.selectAll(self.element_id, limit, page)
            for tabla in tablas:
                print "{0}: {1}".format(tabla.id, tabla)
            
            if page > 1:
                print "To go to the previous page press < "
            
            if (page * limit) < quantity_tables:
                print "To go to the next page press > "
                
            option = raw_input("Select the number to edit or 0 to come back\n")
            try:
                if option == "<":
                    self.list_tables(limit, page - 1)
                    number = 0
                elif option == ">":
                    self.list_tables(limit, page + 1)
                    number = 0
                else:
                    number = int(option)
                    if number != 0:
                        self.edit_table(number)
                        
            except ValueError:
                print "It has to be a number"        
        
        return True

    def list_connection(self, limit = setup_options.getLimit(), page = 1):
        print "======= Listing conectors ======="
        print "===========In case you want to delete a project press d plus the number =========================="
        quantity_connectors = self.conector_db.retrieveAllCount(self.element_id)
        number = 1
        while number != 0:
            conectores = self.conector_db.selectAll(self.element_id, limit, page)
            for conector in conectores:
                print "{0}: {1}".format(conector.id, conector)
            
            if page > 1:
                print "To go to the previous page press < "
            
            if (page * limit) < quantity_connectors:
                print "To go to the next page press > "
                
            option = raw_input("Select the number to edit or 0 to come back\n")
            try:
                if option == "<":
                    self.list_connection(limit, page - 1)
                    number = 0
                elif option == ">":
                    self.list_connection(limit, page + 1)
                    number = 0
                else:
                    number = int(option)
                    if number != 0:
                        self.edit_conector(number)
                        
            except ValueError:
                print "It has to be a number"
        return True
                
    def start_up(self):
        aux = self.proyectos_db.findOne(self.element_id)
        if aux == None:
            print "Ups... None finded"
            return
        
        main_menu_text = {1 : 'Create connection', 2: 'List Connections', 3: 'Populate tables', 4: 'List tables', 5 : 'Back'}
        main_menu_options = {1 : self.new_connection, 2: self.list_connection, 3: self.populate_tables ,4 : self.list_tables, 5 : self.return_false}

        options = { 'main' : { 'text' : main_menu_text, 'options' : main_menu_options}}
        start_point = 'main'

        selected = start_point
        
        keep_going = True
        
        while keep_going:
            print "========== Project: {0} ================".format(aux.nombre)
            displayed = options[selected]['text']
            sel_options = options[selected]['options']
        
            for k, v in displayed.iteritems():
                print " {0} - {1}".format(k, v)
            
            selection = raw_input("[Selection] >") 
            selection_int = 0
            try:
                #print selection
                selection_int = int(selection)
                function = sel_options[selection_int] 
                keep_going = function()
            except ValueError:
                print "It has to be a number"        
class ProyectoTerminal(object):
    def __init__(self, elementId, db):
        print "start"
        self.element_id = elementId
        self.proyectos_db = db
        self.conector_db = ConectorSqlite()
        self.tablas_db = TablasSqlite()

    def return_false(self):
        return False

    def new_connection(self):
        print "========== Create a new connection ================"
        aux = Conector()
        aux.proyecto_id = self.element_id
        aux.tipo = 1

        has_error = True
        host = ""
        while has_error:
            host = raw_input("[Host] > ")
            if host != "":
                has_error = False
        aux.host = host

        has_error = True
        port = ""
        while has_error:
            port = raw_input("[Port] > ")
            if port != "":
                has_error = False
        aux.port = port

        has_error = True
        user = ""
        while has_error:
            user = raw_input("[User] > ")
            if user != "":
                has_error = False
        aux.user = user

        has_error = True
        password = ""
        while has_error:
            password = raw_input("[Password] > ")
            if password != "":
                has_error = False
        aux.password = password

        schema = ""
        schema = raw_input("[Schema] > ")
        aux.schema = schema

        has_error = True
        master = 0
        while has_error:
            try:
                aux_master = raw_input("[Master] > ")
                master = int(aux_master)
                if master == 0 or master == 1:
                    has_error = False
            except ValueError:
                print "It has to be a number"
        aux.master = master

        aux.id = self.conector_db.insert_element(aux)
        return True

    def edit_table(self, tableId):
        aux = self.tablas_db.findOne(tableId)
        print "============== Editing table =================="
        print aux
        print "============ Choose options ==================="

        has_error = True
        use_all = 0
        while has_error:
            try:
                aux_master = raw_input(
                    "[Use all (1 for All and 0 for None)] > ")
                use_all = int(aux_master)
                if use_all == 0 or use_all == 1:
                    has_error = False
            except ValueError:
                print "It has to be a number"
        aux.use_all = use_all

        condition = ""
        condition = raw_input("[Condition] > ")
        if condition != "":
            aux.condition = condition

        self.tablas_db.update_element(aux)

        print "Dont doing anything..."

    def populate_tables(self):
        stealLogic = StealerLogic()
        stealLogic.populate_tables(self.element_id)
        return True

    def edit_conector(self, conectorId):

        print "Dont doing anything..."

    def list_tables(self, limit=setup_options.getLimit(), page=1):
        print "============= Listing tables =================="
        quantity_tables = self.tablas_db.retrieveAllCount(self.element_id)
        number = 1
        while number != 0:
            tablas = self.tablas_db.selectAll(self.element_id, limit, page)
            for tabla in tablas:
                print "{0}: {1}".format(tabla.id, tabla)

            if page > 1:
                print "To go to the previous page press < "

            if (page * limit) < quantity_tables:
                print "To go to the next page press > "

            option = raw_input("Select the number to edit or 0 to come back\n")
            try:
                if option == "<":
                    self.list_tables(limit, page - 1)
                    number = 0
                elif option == ">":
                    self.list_tables(limit, page + 1)
                    number = 0
                else:
                    number = int(option)
                    if number != 0:
                        self.edit_table(number)

            except ValueError:
                print "It has to be a number"

        return True

    def list_connection(self, limit=setup_options.getLimit(), page=1):
        print "======= Listing conectors ======="
        print "===========In case you want to delete a project press d plus the number =========================="
        quantity_connectors = self.conector_db.retrieveAllCount(
            self.element_id)
        number = 1
        while number != 0:
            conectores = self.conector_db.selectAll(self.element_id, limit,
                                                    page)
            for conector in conectores:
                print "{0}: {1}".format(conector.id, conector)

            if page > 1:
                print "To go to the previous page press < "

            if (page * limit) < quantity_connectors:
                print "To go to the next page press > "

            option = raw_input("Select the number to edit or 0 to come back\n")
            try:
                if option == "<":
                    self.list_connection(limit, page - 1)
                    number = 0
                elif option == ">":
                    self.list_connection(limit, page + 1)
                    number = 0
                else:
                    number = int(option)
                    if number != 0:
                        self.edit_conector(number)

            except ValueError:
                print "It has to be a number"
        return True

    def start_up(self):
        aux = self.proyectos_db.findOne(self.element_id)
        if aux == None:
            print "Ups... None finded"
            return

        main_menu_text = {
            1: 'Create connection',
            2: 'List Connections',
            3: 'Populate tables',
            4: 'List tables',
            5: 'Back'
        }
        main_menu_options = {
            1: self.new_connection,
            2: self.list_connection,
            3: self.populate_tables,
            4: self.list_tables,
            5: self.return_false
        }

        options = {
            'main': {
                'text': main_menu_text,
                'options': main_menu_options
            }
        }
        start_point = 'main'

        selected = start_point

        keep_going = True

        while keep_going:
            print "========== Project: {0} ================".format(aux.nombre)
            displayed = options[selected]['text']
            sel_options = options[selected]['options']

            for k, v in displayed.iteritems():
                print " {0} - {1}".format(k, v)

            selection = raw_input("[Selection] >")
            selection_int = 0
            try:
                #print selection
                selection_int = int(selection)
                function = sel_options[selection_int]
                keep_going = function()
            except ValueError:
                print "It has to be a number"
    def __init__(self):

        self.conector_db = ConectorSqlite()
        self.tablas_db = TablasSqlite()
class StealerLogic(object):
    def __init__(self):

        self.conector_db = ConectorSqlite()
        self.tablas_db = TablasSqlite()

    def populate_tables(self, projectId):
        """ 
        Mido el tiempo del script - INICIO
        """
        a = datetime.now()
        print a
        quantity_connectors = self.conector_db.retrieveAllCount(projectId)
        if quantity_connectors != 2:
            raise "It must have two connectors"

        else:
            self.tablas_db.delete_element(projectId)

            conectores = self.conector_db.selectAll(projectId, 2, 1)
            master = None
            slave = None
            for conector in conectores:
                if conector.master == 0:
                    slave = conector.getConnectionString()
                elif conector.master == 1:
                    master = conector.getConnectionString()

            print master
            print slave

            master_connection = cx_Oracle.connect(master)
            master_connection.clientinfo = 'python 2.7.3 @ rsantellan'
            master_connection.module = 'Master database stealer'
            master_connection.action = 'Master database stealer selects'
            print("Master Oracle DB version: " + master_connection.version)
            print("Master Oracle client encoding: " +
                  master_connection.encoding)

            slave_connection = cx_Oracle.connect(master)
            slave_connection.clientinfo = 'python 2.7.3 @ rsantellan'
            slave_connection.module = 'Master database stealer'
            slave_connection.action = 'Master database stealer selects'
            print("Slave Oracle DB version: " + slave_connection.version)
            print("Slave Oracle client encoding: " + slave_connection.encoding)
            """ 
            Creo el cursor.
            """
            master_cursor = master_connection.cursor()
            slave_cursor = slave_connection.cursor()
            """ 
            Selecciono todas las tablas que corresponden a ese usuario
            """
            query_all_tables = "SELECT table_name FROM user_tables"

            master_cursor.execute(query_all_tables)

            rows_all_tables = master_cursor.fetchall()

            for row in rows_all_tables:

                #Have to calculate how many register the table have
                master_global_count = "SELECT COUNT(*) FROM %s" % row[0]
                master_cursor.execute(master_global_count)
                rowQuantity = master_cursor.fetchone()
                aux = Tabla()
                aux.proyecto_id = projectId
                aux.name = row[0]
                aux.quantity_master = int(rowQuantity[0])
                checked = False
                try:

                    #Checking that in the database exists
                    slave_cursor.execute(master_global_count)
                    rowQuantitySlave = slave_cursor.fetchone()
                    checked = True
                except Exception, e:
                    print e

                aux.checked = checked
                #check that in the other
                self.tablas_db.insert_element(aux)

            master_connection.close()
            slave_connection.close()
        """ 
            Mido el tiempo del script - FIN
        """
        b = datetime.now()
        print b

        c = b - a
        print c
 def __init__(self):
     
     self.conector_db = ConectorSqlite()
     self.tablas_db = TablasSqlite()
class StealerLogic(object):
    
    def __init__(self):
        
        self.conector_db = ConectorSqlite()
        self.tablas_db = TablasSqlite()
        
    def populate_tables(self, projectId):
        """ 
        Mido el tiempo del script - INICIO
        """
        a = datetime.now()
        print a
        quantity_connectors = self.conector_db.retrieveAllCount(projectId)
        if quantity_connectors != 2:
            raise "It must have two connectors"
            
        else:
            self.tablas_db.delete_element(projectId)
            
            conectores = self.conector_db.selectAll(projectId, 2, 1)
            master = None
            slave = None
            for conector in conectores:
                if conector.master == 0:
                    slave = conector.getConnectionString()
                elif conector.master == 1:
                    master = conector.getConnectionString()
            
            print master
            print slave
            
            master_connection = cx_Oracle.connect(master)
            master_connection.clientinfo = 'python 2.7.3 @ rsantellan'
            master_connection.module = 'Master database stealer'
            master_connection.action = 'Master database stealer selects'
            print ("Master Oracle DB version: " + master_connection.version)
            print ("Master Oracle client encoding: " + master_connection.encoding)
            
            slave_connection = cx_Oracle.connect(master)
            slave_connection.clientinfo = 'python 2.7.3 @ rsantellan'
            slave_connection.module = 'Master database stealer'
            slave_connection.action = 'Master database stealer selects'
            print ("Slave Oracle DB version: " + slave_connection.version)
            print ("Slave Oracle client encoding: " + slave_connection.encoding)
            """ 
            Creo el cursor.
            """
            master_cursor = master_connection.cursor()
            slave_cursor = slave_connection.cursor()

            """ 
            Selecciono todas las tablas que corresponden a ese usuario
            """
            query_all_tables = "SELECT table_name FROM user_tables"
            
            master_cursor.execute(query_all_tables)
            
            rows_all_tables = master_cursor.fetchall()
            
            for row in rows_all_tables:
                
                #Have to calculate how many register the table have
                master_global_count = "SELECT COUNT(*) FROM %s" % row[0];
                master_cursor.execute(master_global_count)
                rowQuantity = master_cursor.fetchone()
                aux = Tabla()
                aux.proyecto_id = projectId
                aux.name = row[0]
                aux.quantity_master = int(rowQuantity[0])
                checked = False
                try:
                    
                    #Checking that in the database exists
                    slave_cursor.execute(master_global_count)
                    rowQuantitySlave = slave_cursor.fetchone()
                    checked = True
                except Exception, e:
                    print e
                     
                aux.checked = checked
                #check that in the other 
                self.tablas_db.insert_element(aux)
                
            
            master_connection.close()
            slave_connection.close()
                
            
        """ 
            Mido el tiempo del script - FIN
        """
        b = datetime.now()
        print b

        c = b - a
        print c