# encoding:utf-8
# name:mod_db.py


'''
使用方法：1.在主程序中先实例化DB Mysql数据库操作类。
      2.使用方法:db=database()  db.fetch_all("sql")
'''


from __future__ import division

import pymysql
import pymysql.cursors
from db import mod_config
from elasticsearch import Elasticsearch

DB = "database"
DBNAME = mod_config.getConfig(DB, 'dbname')
DBHOST = mod_config.getConfig(DB, 'dbhost')
DBUSER = mod_config.getConfig(DB, 'dbuser')
DBPWD = mod_config.getConfig(DB, 'dbpassword')
DBCHARSET = mod_config.getConfig(DB, 'dbcharset')
DBPORT = mod_config.getConfig(DB, "dbport")

ES = "es"
ESHOST = mod_config.getConfig(ES, 'eshost')
ESUSER = mod_config.getConfig(ES, 'esuser')
ESPWD = mod_config.getConfig(ES, 'espassword')
ESCHARSET = mod_config.getConfig(ES, 'escharset')
ESPORT = mod_config.getConfig(ES, "esport")



# 数据库操作类
class DataBase:
    # 注，python的self等于其它语言的this
    def __init__(self, dbname=None, dbhost=None):
        # 这里的None相当于其它语言的NULL
        if dbname is None:
            self._dbname = DBNAME
        else:
            self._dbname = dbname
        if dbhost is None:
            self._dbhost = DBHOST
        else:
            self._dbhost = dbhost

        self._dbuser = DBUSER
        self._dbpassword = DBPWD
        self._dbcharset = DBCHARSET
        self._dbport = int(DBPORT)
        self._conn = self.connectMySQL

        if (self._conn):
            self._cursor = self._conn.cursor()

    # 数据库连接
    @property
    def connectMySQL(self):
        conn = False
        try:
            conn = pymysql.connect(host=self._dbhost,
                                   user=self._dbuser,
                                   passwd=self._dbpassword,
                                   db=self._dbname,
                                   port=self._dbport,
                                   cursorclass=pymysql.cursors.DictCursor,
                                   charset=self._dbcharset,
                                   autocommit=True
                                   )
        except Exception as data:
            print("connect database failed, %s" % data)
            conn = False
        return conn

    # 获取查询结果集
    def fetch_all(self, sql):
        res = ''
        if (self._conn):
            try:
                self._cursor.execute(sql)
                res = self._cursor.fetchall()
            except Exception as data:
                res = False
                print("query database exception, %s" % data)
        return res
    def fetch_one(self, sql):
        res = ''
        if (self._conn):
            try:
                self._cursor.execute(sql)
                res = self._cursor.fetchone()
            except Exception as data:
                res = False
                print("query database exception, %s" % data)
        return res

    def update(self, sql, params):
        flag = False
        if (self._conn):
            try:
                print(sql,"==============================")
                self._cursor.execute(sql, params)
                self._conn.commit()
                flag = True
            except Exception as data:
                flag = False
                print("update database exception, %s" % data)

        return flag


    def insert_batch(self, sql):
        flag = False
        if (self._conn):
            try:
                self._cursor.execute(sql)
                flag = True
                self._conn.commit()
            except Exception as data:
                flag = False
                print("update database exception, %s" % data)
        return flag


    # 关闭数据库连接
    def close(self):
        if (self._conn):
            try:
                if (type(self._cursor) == 'object'):
                    self._cursor.close()
                if (type(self._conn) == 'object'):
                    self._conn.close()
            except Exception as data:
                print("close database exception, %s,%s,%s" % (data, type(self._cursor), type(self._conn)))

    def roll_back(self):
        if (self._conn):
            try:
               self._conn.rollback()
            except Exception as data:
                print("db rollback exception, %s" % data)

    def get_cursor(self):
        return self._cursor

    def get_conn(self):
        return self._conn


class EsBase:
    def __init__(self, eshost=None):
        # 这里的None相当于其它语言的NULL

        if eshost is None:
            self._eshost = ESHOST
        else:
            self._eshost = eshost

        self._esuser = ESUSER
        self._espassword = ESPWD
        self._escharset = ESCHARSET
        self._esport = int(ESPORT)
        self._connes = self.connectES

        # if (self._conn):
        #     self._cursor = self._conn.cursor()
    @property
    def connectES(self):
        es = False
        try:
            es = Elasticsearch(
                [self._eshost],
                http_auth=(self._esuser, self._espassword),
                port=self._esport,timeout = 30)


        except Exception as data:
            print("connect es failed, %s" % data)
            es = False
        return es

    def select(self, index=None,body=None):
        res = ''
        if (self._connes):
            try:
                res = self._connes.search(index = index, body = body)
                # res = self._cursor.fetchall()
            except Exception as data:
                res = False
                print("query esbase exception, %s" % data)
            print (res)
        return res