# -*- coding: utf_8 -*-
# 表名: address_book
# 作者: 陈磊
# 时间: 2019-12-09


from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, VARCHAR, 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 AddressBook(Base):
    """
    地址簿
    """
    __tablename__ = "address_book"

    id = Column(Integer, primary_key=True)
    name = Column(VARCHAR(255), comment="名称")
    iplist = Column(VARCHAR(255), comment="ip范围")
    available = Column(Integer, comment="可用性 1-可用0-禁用")
    checktype = Column(Integer, comment="1：agnet 2：snmp  3：icmp")
    ruleid = Column(Integer, comment="规则id")
    delay = Column(VARCHAR(255), comment="间隔时间")


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

        self.table = AddressBook

    def select_all_from_allKeys(self, session, _id=None, name=None):
        """
        :param session: 指针
        :param _id:
        :param name:
        :return: 查询结果
        """
        self.log.debug("查询数据库:")
        try:
            base = UtilsDataBase()
            base.add_param(_key="id", value=_id)
            base.add_param(_key="name", value=name)
            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_like_name(self, session, name):
        """
        :param session: 指针
        :param name:
        :return:
        """
        self.log.debug("查询数据库:")
        try:
            self.log.debug("删除相关测试数据")
            session.query(self.table).filter(self.table.name.like("%" + str(name) + "%")).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
