#!/usr/bin/env python3  
# -*- coding: utf-8 -*-  
"""
@Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
@AUTHOR: ASJRD018
@NAME: Ansjer
@software: PyCharm
@DATE: 2018/6/15 14:18
@Version: python3.6
@MODIFY DECORD:ansjer dev
@file: mongodb.py
@Contact: chanjunkai@163.com
"""
# !/usr/bin/python3
import pymongo
import math
from Ansjer.config import SERVER_TYPE
# SERVER_TYPE = 'local'

class mongodb(object):

    def __init__(self):
        # sysstr = platform.system()
        # if (sysstr == "Windows"):
        #     myclient = pymongo.MongoClient('mongodb://192.168.136.45:27017/')
        # elif (sysstr == "Linux"):
        #     print("Call Linux tasks")
        #     myclient = pymongo.MongoClient()
        if SERVER_TYPE == 'Ansjer.local_settings':
            self.myclient = pymongo.MongoClient('mongodb://192.168.136.45:27017/')
            self.db =  self.myclient['ansjer']
        elif SERVER_TYPE == 'Ansjer.test_settings':
            self.myclient = pymongo.MongoClient()
            self.db =  self.myclient['test_ansjer']
        elif SERVER_TYPE == 'Ansjer.formal_settings':
            self.myclient = pymongo.MongoClient()
            self.db = self.myclient['ansjer']

    # 创建mongodb的数据库名称
    def check_db_exist(self, database):
        dblist = self.myclient.database_names()
        if database in dblist:
            print("数据库存在")
            return True
        else:
            print("数据库不存在")
            return False


    def insert_one(self, col, data):
        column = self.db[col]
        res = column.insert_one(data)
        return res.inserted_id

    def findAll(self, col,page,line,query):
        collist = self.db.collection_names()
        if col in collist:  # 判断 customers 集合是否存在
            # qs = self.db[col].find()
            if int(page) < 0:
                count = mdb.cout(col=col, query=query)
                total = math.ceil(count / int(line))
                page = int(total) + int(page) + 1
            qs = self.db[col].find(query).sort("_id", -1)
            count = qs.count()
            if page != 0 and line != 0:
                qs = qs.skip((page - 1) * 10).limit(line)
            # print(count)
            data = []
            for q in qs:
                q.pop('_id')
                if 'et' in q:
                    q.pop('et')
                data.append(q)
            res_dict = {'data': data, 'count': count}
            return res_dict
        else:
            print("集合不存在！")
            return False

    #获取col总数
    def cout(self,col,query):
        collist = self.db.collection_names()
        if col in collist:  # 判断 customers 集合是否存在
            # qs = self.db[col].find()
            qs = self.db[col].find(query)
            count = qs.count()
        return count

    # 删除集合（//删除表）
    def drop_col(self,col):
        column = self.db[col]
        column.drop()
        return

if __name__ == '__main__':
    mdb = mongodb()
    col = "log_device_operation"
    # col = "log_access"
    # mdb.drop_col(col)
    # exit()
    # data = {"name": "111", "address": "Lowstreet 27"}
    # flag = mdb.insert_one(col=col, data=data)
    # qs = mdb.findAll(col=col, page=1, line=10,query={'UID':'C2887N9EBS87ZAT1111A'})
    # print(qs)
    '''创建索引'''
    # from pymongo import ASCENDING, DESCENDING
    ss = mdb.db[col].create_index([('type',1)])
    # ss = mdb.db[col].create_index([('time',1)])
    #print(ss)
    ''''''
    '''
    604800
    '''
    '''
    增加过期时间
    '''
    mdb.db[col].create_index([("et", 1)], expireAfterSeconds=604800)
    # mdb.db[col].create_index([("et", 1)], expireAfterSeconds=1209600)
    '''
    删除索引
    '''