#!/usr/bin/env python3
"""
URI manipulation.
"""

import pathlib
import urllib.parse

FILENAME = "meta.yaml"


class URITransformer:
    """
    Transform URIs, including file paths.
    """

    def __init__(self, uri):
        self.parts = urllib.parse.urlsplit(uri)

    def __str__(self):
        return urllib.parse.urlunsplit(self.parts)

    def __hash__(self):
        return hash(str(self))

    def __eq__(self, other):
        return str(self) == str(other)

    def copy(self, path=None):
        """
        Get a copy of this instance.
        """
        cpy = self.__class__(str(self))
        if path is not None:
            cpy.path = path
        return cpy

    @property
    def scheme(self):
        """
        The URI scheme.
        """
        return self.parts.scheme

    @property
    def is_local_file(self):
        """
        True if the URI points to a local path, else False. The path may not exist.
        """
        scheme = self.scheme
        return (not scheme) or scheme.lower() == "file"

    @property
    def path(self):
        """
        The path.
        """
        return pathlib.Path(self.parts.path)

    @path.setter
    def path(self, path):
        if self.is_local_file and self.path.is_absolute():
            path = path.resolve()
        # Despite the understore, _replace is supported in the official
        # documentation.
        self.parts = self.parts._replace(path=str(path))
