import logging

from graphene.storage.base.string_store import *
from graphene.storage.intermediate.general_store_manager import *


class StringManager(object):
    """
    Handles common reading/writing operations for variable-length strings
    """

    def __init__(self, filename, block_size=10):
        """
        Creates a StringManager instance which handles reading/writing
        variable-length strings (ASCII or Unicode)

        :param filename: Name of file where strings will be read/written to
        :type filename: str
        :param block_size: Length of string block
        :type block_size: int
        :return: String manager instance to handle general reading/writing
                 operations
        :rtype: StringManager
        """
        # Size of string blocks
        self.blockSize = block_size
        # Create a manager for the string store
        self.storeManager = GeneralStoreManager(StringStore(filename, block_size))
        self.logger = logging.getLogger(self.__class__.__name__)

    def __del__(self):
        del self.storeManager

    def write_string(self, string):
        """
        Write the given variable-length string to the string store

        :param string: String to write
        :type string: str | unicode
        :return: Starting index of the stored string
        :rtype: int
        """
        # Encode the given string to store
        string = self.encode(string)
        # Get parts of string (separated based on the block size)
        string_parts = self.split_string(string)
        # Number of parts
        length = len(string_parts)
        # Get IDs to store the blocks into
        ids = self.storeManager.get_indexes(length)

        # TODO: refactor length to amount
        # Block of length 1
        if length == 1:
            kwargs = {'in_use': False,
                      'previous_block': 0,
                      'length': length,
                      'next_block': 0,
                      'string': string_parts[0]}
        else:
            kwargs = {'in_use': False,
                      'previous_block': 0,