# Copyright 2018 ICON Foundation
#
# 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 os

import plyvel


class TbearsDB:
    @staticmethod
    def make_db(path: str, create_if_missing: bool = True) -> plyvel.DB:
        if not os.path.exists(path):
            os.makedirs(path)
        return plyvel.DB(path, create_if_missing=create_if_missing)

    def __init__(self, db: plyvel.DB) -> None:
        """Constructor

        :param db: plyvel DB instance
        """
        self._db = db

    def get(self, key: bytes) -> bytes:
        """Get value from db using key

        :param key: db key
        :return: value indicated by key otherwise None
        """
        return self._db.get(key)

    def put(self, key: bytes, value: bytes) -> None:
        """Put value into db using key.

        :param key: (bytes): db key
        :param value: (bytes): data to be stored in db
        """
        self._db.put(key, value)

    def delete(self, key: bytes) -> None:
        """Delete a row

        :param key: delete the row indicated by key.
        """
        self._db.delete(key)

    def close(self) -> None:
        """Close db
        """
        if self._db:
            self._db.close()
            self._db = None

    def create_write_batch(self) -> object:
        return self._db.write_batch(transaction=True)

    @staticmethod
    def write_batch(write_batch, key: bytes, value: bytes):
        write_batch.put(key, value)

    @staticmethod
    def commit_write_batch(write_batch):
        write_batch.write()

    def iterator(self) -> iter:
        return self._db.iterator()
