import posixpath

from parallels.core.dump.file_adapters import TarFileAdapter, ZipFileAdapter
from parallels.plesk.source.plesk.hosting_description.dump.base_dump import BaseDump


class FileDump(BaseDump):
    """
    The dump is a file
    """
    def __init__(self, path, backup_prefix=None, backup_id=None):
        self._dump_reader = TarFileAdapter(path) if path.endswith('.tar') else ZipFileAdapter(path)
        self._files = self._dump_reader.get_names()
        super(FileDump, self).__init__(path, backup_prefix, backup_id)

    def _list_files(self):
        """
        :return: [str|unicode]
        """
        return self._files

    def _get_content(self, name):
        """
        :type name: str|unicode
        :return: str|unicode
        """
        return self._dump_reader.extract(name).read()

    def _path_exists(self, path):
        """
        :type path: str|unicode
        :return: bool
        """
        for f in self._files:
            if f.startswith(path + '/') or f == path:
                return True
        return False

    def _list_dir(self, path):
        """
        :type path: str|unicode
        :return: [str|unicode]
        """
        list_dir = []
        for f in self._files:
            if path == '.':
                item = f
            else:
                if not f.startswith(path + '/'):
                    continue
                start_pos = len(path) + 1
                item = f[start_pos:]
            end_pos = item.find('/')
            if end_pos != -1:
                item = item[:end_pos]
            if item not in list_dir:
                list_dir.append(item)
        return list_dir

    def _is_dir(self, path):
        """
        :type path: str|unicode
        :return: bool
        """
        for f in self._files:
            if f.startswith(path + '/'):
                return True
        return False

    def _join_path(self, path1, path2):
        """
        :type path1: str|unicode
        :type path2: str|unicode
        :return: str|unicode
        """
        return posixpath.join(path1, path2)

    def _path_sep(self):
        """
        :return: str|unicode
        """
        return posixpath.sep
