# -*- coding: utf-8 -*-
#
# Copyright 2017 dpa-infocom GmbH
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import dsnparse
import logging
from datetime import datetime
from pymongo import DESCENDING
from motor.motor_asyncio import AsyncIOMotorClient
from bson.objectid import ObjectId
from livebridge.storages.base import BaseStorage


logger = logging.getLogger(__name__)


class MongoStorage(BaseStorage):

    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(MongoStorage, cls).__new__(cls)
            logger.debug("MongoDB client: {}".format(cls._instance))
        return cls._instance

    def __init__(self, **kwargs):
        self.dsn = kwargs.get("dsn", None)
        self.table_name = kwargs.get("table_name")
        self.control_table_name = kwargs.get("control_table_name")

        # get db name
        info = dsnparse.parse(self.dsn)
        self.db_name = info.paths.pop() if len(info.paths) == 1 else ""
        assert self.db_name != "", "No database name provided in DSN connection string"

    @property
    async def db(self):
        if hasattr(self, "_db") and self._db:
            return self._db
        logger.debug("Connecting to {}".format(self.dsn))
        client = AsyncIOMotorClient(self.dsn)
        self._db = client[self.db_name]
        return self._db

    async def setup(self):
        """Setting up MongoDB collections, if they not exist."""
        try:
            db = await self.db
            collections = await db.list_collection_names()
            created = False
            if self.table_name not in collections:
                # create table
                logger.info("Creating MongoDB collection [{}]".format(self.table_name))
                await db.create_collection(self.table_name)
                await db[self.table_name].create_index([("target_id", DESCENDING), ("post_id", DESCENDING)])
                created = True