"""
Package for parsing axipy plugins metadata.

Does not depend on axipy itself.
"""

import json
from pathlib import Path
from typing import List, Union

from .folder_parser import FolderParser
from .package_parser import ARCHIVE_EXTENSION, PackageParser
from .parser import MANIFEST_FILE_NAME

__all__: List[str] = [
    "read_metadata_params",
    "read_metadata",
    "install",
    "MANIFEST_FILE_NAME",
    "ARCHIVE_EXTENSION",
    "PackageParser",
    "FolderParser",
]


def read_metadata_params(plugin_path: Union[str, Path]) -> dict:
    known_parsers = [PackageParser, FolderParser]
    supported_parsers = filter(lambda parser_arg: parser_arg.supports(plugin_path), known_parsers)
    supported_parser = next(supported_parsers, None)
    if supported_parser is None:
        raise RuntimeError(f"No known parser supports {plugin_path}")
    parser_ = supported_parser()
    return parser_.parse(plugin_path)


def read_metadata(plugin_path: str) -> str:
    params = read_metadata_params(plugin_path)
    return json.dumps(params)


def install(package_file: str, destination: str) -> None:
    PackageParser.install(package_file, Path(destination))


def test_network() -> bool:
    from urllib.request import urlopen

    try:
        urlopen("https://www.python.org")
        return True
    except (Exception,):
        return False
