# import sqlite3
# from .SQLite_queries import *
from .ServiceDefs import *
import datetime
from flask import g
from pymongo import MongoClient
from .constants import *
import json
# from libs.interfaces.ExampleLabels import *



class DatabaseOps():


    def __init__(self, db_conection_dict, errors_fname):
        self.db_conection_dict = db_conection_dict
        self.errors_fname = errors_fname
        # self.client = self.client = MongoClient(host = self.db_conection_dict[SETTING_LABELS_DATABASE_HOST],
        #                                         port = int(self.db_conection_dict[SETTING_LABELS_DATABASE_PORT]),
        #                                         serverSelectionTimeoutMS = 2000)
        self.client = MongoClient(
            'mongodb://' + db_conection_dict['db_username'] + ':' + db_conection_dict['db_password'] + '@' +
            db_conection_dict['db_host'] + ':27017/' + db_conection_dict['db_name'], serverSelectionTimeoutMS=2000)
        self.db = self.client[db_conection_dict[SETTING_LABELS_DATABASE_NAME]]
        self.collection = self.db[db_conection_dict[SETTING_LABELS_COLLECTION]]
        self.sds_collection = self.db[db_conection_dict[SETTING_LABELS_SDS_COLLECTION]]


    def test_db_connection(self):
        try:
            info = self.client.server_info()
            return True
        except Exception as ex:
            ServiceDefs.ReportException(self.errors_fname, ex)
            return False


    def read_example_labels(self, img_basename):
        try:
            found = self.collection.find_one({"strBaseImageFilename": img_basename})
            if found:
                del found['_id']
                found_str = json.dumps(found).replace(JSON_TYPE_KEY, '$type').replace(JSON_VALUE_KEY, '$values')
                return found_str
            else:
                return None
        except Exception as ex:
            ServiceDefs.ReportException(self.errors_fname, ex)
            return None


    def insert_example_labels(self, example_labels):
        try:
            self.collection.delete_many({"strBaseImageFilename": example_labels['strBaseImageFilename']})
            example_id = self.collection.insert_one(example_labels).inserted_id
            return example_id
        except Exception as ex:
            ServiceDefs.ReportException(self.errors_fname, ex)
            return False


    def insert_example_sds_labels(self, example_sds_labels):
        try:
            self.sds_collection.delete_many({"strBaseImageFilename": example_sds_labels['strBaseImageFilename']})
            example_id = self.collection.insert_one(example_sds_labels).inserted_id
            return example_id
        except Exception as ex:
            ServiceDefs.ReportException(self.errors_fname, ex)
            return False


    def remove_label(self, label_uid):
        raise NotImplementedError()

    def update_label(self, label):
        raise NotImplementedError()
