# -*- coding: utf_8 -*-
# 表名: interface
# 作者: 陈磊
# 时间: 2019-11-11


from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, VARCHAR, BIGINT, SMALLINT, DATETIME, DECIMAL, BigInteger, FLOAT, NUMERIC, TEXT
from sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound
from sqlalchemy import or_

from WorkUtils.UtilsLog import UtilsLog
from WorkUtils.UtilsDataBase import UtilsDataBase

import time

Base = declarative_base()


class Interface(Base):
    """
    主机接口信息表
    """
    __tablename__ = "interface"

    interfaceid = Column(Integer, primary_key=True)
    hostid = Column(Integer)
    main = Column(Integer)
    type = Column(Integer)
    useip = Column(Integer)
    ip = Column(VARCHAR(64))
    dns = Column(VARCHAR(255))
    port = Column(VARCHAR(64))
    bulk = Column(Integer)


class DataInterface(object):
    def __init__(self):
        self.log = UtilsLog()
        self.log.info(self.__class__)

        self.table = Interface

    def select_all_from_allKeys(self, session, interfaceid=None, hostid=None, ip=None, port=None):
        """
        :param session: 指针
        :param interfaceid:
        :param hostid:
        :param ip:
        :param port:
        :return: 查询结果
        """
        self.log.debug("查询数据库:")
        self.log.debug("interfaceid: %s" % interfaceid)
        self.log.debug("hostid: %s" % hostid)
        self.log.debug("ip: %s" % ip)
        self.log.debug("port: %s" % port)
        try:
            base = UtilsDataBase()
            base.add_param(_key="interfaceid", value=interfaceid)
            base.add_param(_key="hostid", value=hostid)
            base.add_param(_key="ip", value=ip)
            base.add_param(_key="port", value=port)
            sql_rep = session.query(self.table).filter_by(**base.param).all()
            self.log.debug(sql_rep)
            session.close()
            return sql_rep
        except UtilsDataBase().errors as error:
            self.log.error("异常:")
            self.log.error(error)
            session.close()
            return error

    def delete_hostid(self, session, hostid):
        """
        :param session: 指针
        :param hostid:
        :return:
        """
        self.log.debug("查询数据库:")
        try:
            self.log.debug("删除相关测试数据")
            session.query(self.table).filter_by(hostid=hostid).delete(synchronize_session=False)
            # session.delete(sql)
            session.commit()
            session.close()
            self.log.debug("删除成功")
            return True
        except UtilsDataBase().errors as error:
            self.log.error("异常:")
            self.log.error(error)
            session.close()
            return error
