#!/usr/bin/env python

import MySQLdb
import _mysql_exceptions

class FilesMonitoring:
    LETTERS = '0123456789abcdef'
    SQL_CREATE_TABLE_TEMPLATE_FILENAME = 'sql/CreateTableTemplate.sql'

    def __init__(self):
        self.old_db = MySQLdb.connect('ippc11', 'ippuser', 'ipp', 'FilesMonitoring')
        self.new_db = MySQLdb.connect('ippc11', 'ippuser', 'ipp', 'DisksMonitoring')
        self.create_table_template = ''
        for line in open(FilesMonitoring.SQL_CREATE_TABLE_TEMPLATE_FILENAME):
            self.create_table_template += line

    def close(self):
        self.old_db.close()
        self.new_db.close()

    def convert_node(self, node):
        print 'Converting data for storage node [%s]' % node
        for letter1 in FilesMonitoring.LETTERS:
            for letter2 in FilesMonitoring.LETTERS:
                oldtable = 'Files_%s_%s%s' % (node, letter1, letter2)
                newtable = '%s_%s%s' % (node, letter1, letter2)
                self.convert_table(oldtable, newtable)

    def convert_table(self, oldtable, newtable):
        self.create_table_in_new_database(newtable)
        query_select = """SELECT 
filename, neb_ins_id, subdirname, nebkey, size, md5sum, role, stage, lifetime, creation_date, last_check 
FROM %s""" % oldtable
        old_cursor = self.old_db.cursor()
        old_cursor.execute(query_select)
        print oldtable, len(old_cursor.fetchall())

    def create_table_in_new_database(self, table):
        new_cursor = self.new_db.cursor()
        # print self.create_table_template.replace('@TABLE_NAME@', table)

if __name__ == '__main__':
    fm = FilesMonitoring()
    # for node in open('/home/panstarrs/schastel/local/share/ippMhpccStorageNodes'):
    for node in ['ipp027\n']:
        fm.convert_node(node[:-1])
    fm.close()
