# -*- coding: utf-8 -*-
from models.rack import Rack
from models.datacenter import Datacenter
from sqlalchemy import *
from config import MIGRATE_DATABSE_URI
from application import db

class rackmigrate:
    def run(self):
        db.engine.execute("truncate table rack")
        engine = create_engine(MIGRATE_DATABSE_URI, encoding='utf-8',echo=False)
        connection = engine.connect()
        result = connection.execute("select a.name ,a.height,b.name as dc_name from rack as a,location as b where a.location_id=b.id")
        tmplist=[]
        if result:
            tmpdcinfo=Datacenter.query.all()
            dcinfo={}
            for item in tmpdcinfo:
                dcinfo[item.name]=item.id
            for row in result:
                tmp={'name':row['name'],'dc_id':dcinfo[row['dc_name']],'height':row['height']}
                tmplist.append(tmp)
            for item in tmplist:
                tmpinfo=Rack.query.filter(and_(Rack.name==item['name'],Rack.datacenter_id==item['dc_id'])).first()
                if tmpinfo:
                    continue

                target=Rack(item['name'],item['dc_id'],'',item['height'])
                db.session.add(target)
                db.session.commit()
        connection.close()
