# -*- coding: utf-8 -*-
from application import db
from sqlalchemy import *
from models.host import Host
from sqlalchemy import and_
from config import MIGRATE_DATABSE_URI

class Repair:
    def run(self):
        self.zeus_host()
        #self.repair_virtual()
        #self.repair_apc()

    def repair_virtual(self):
        hosts=Host.query.filter(and_(Host.is_virtual==1,Host.parent_id>0)).all()
        if hosts:
            for host in hosts:
                host.type = Host.TYPE_APP
                host.device_id = 0
                db.session.commit()

    def repair_apc(self):
        hosts=Host.query.filter(Host.parent_id>0).all()
        if hosts:
            for host in hosts:
                hostid=host.parent_id
                tmphost=Host.query.filter(Host.id==hostid).first()
                tmphost.type = Host.TYPE_APC
                db.session.commit()

    def zeus_host(self):
        engine = create_engine(MIGRATE_DATABSE_URI, encoding='utf-8',echo=False)
        connection = engine.connect()
        result = connection.execute("select id,application,label from item").fetchall()
        tmplist=[]
        if result:
            for row in result:
                tmp={'id':row['id'],'label':row['label'],'note':row['application']}
                tmplist.append(tmp)
            for items in tmplist:
                    if (items['label'] is None)  or (items['label'] == ""):
                        hostname=connection.execute("select app_name from hosts where item_id = %d" %row['id']).fetchone()
                        if hostname['app_name']:
                            name = hostname['app_name'].strip()
                            ans=Host.query.filter(Host.hostname==name).first()
                    else:
                        label = items['label'].strip()
                        ans=Host.query.filter(Host.hostname==label).first()
                    if ans:
                        if items['note'] is None:
                           items['note'] = ''
                            
                        ans.note = items['note']
                        db.session.commit()
        connection.close()
