import os
import logging

from xdg_base_dirs import xdg_data_home

from whee import Interface

logg = logging.getLogger('whee.fs')


class FsStore(Interface):
    """Implements whee.Interface for Fs backed store
    """

    def __init__(self, passphrase=None, base=xdg_data_home, dbname=None, levels=2):
        self.base = os.path.join(base, dbname)
        os.makedirs(self.base, exist_ok=True)
        self.levels = levels
        logg.info('create fsstore {}'.format(self.base))


    def have(self, k):
        fp = self.to_levelpath(k)
        return os.path.isfile(fp)


    def get(self, k):
        fp = self.to_levelpath(k)
        f = open(fp, 'rb')
        v = f.read()
        f.close()
        logg.debug('fsstore get {} -> {}'.format(k, v))
        return v


    def put(self, k, v, exist_ok=False):
        fp = self.to_levelpath(k)
        if not exist_ok:
            if os.path.exists(fp):
                raise FileExistsError(k.hex())
        dp = os.path.dirname(fp)
        os.makedirs(dp, exist_ok=True)
        f = open(fp, 'wb')
        f.write(v)
        f.close()
        logg.debug('fs put {} under {}'.format(k, fp))


    def delete(self, k):
        fp = self.to_levelpath(k)
        os.unlink(fp)


    def to_levelpath(self, k):
        s = ''
        if isinstance(k, bytes):
            k = k.hex()
        else:
            bytes.fromhex(k)

        l = len(k)
        if l <= self.levels * 2:
            #levels = len(k) - 1
            s = '_/' + k
        else:
            c = 0
            for i in range(self.levels):
                s += k[c:c+2] + '/'
                c += 2
            if c == l:
                s = s[:-1]
            else:
                s += k[c:]
        return os.path.join(self.base, s)
