# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/04_fmu_proxy_interface.ipynb.

# %% auto 0
__all__ = ['NetworkEndpoint', 'DistributedSimulationProxyServer']

# %% ../nbs/04_fmu_proxy_interface.ipynb 3
import json
from dataclasses import dataclass
from typing import Dict, Union, Optional


# %% ../nbs/04_fmu_proxy_interface.ipynb 4
@dataclass
class NetworkEndpoint:
    """Namedtuple class for a network endpoint"""
    address: str
    port: int = None

    def to_dict(self) -> Dict[str, Union[str, int]]:
        """Return dictionary form of the data"""
        return {'address': self.address, 'port': self.port}

    def to_json(self) -> str:
        """Return json form of the data"""
        return json.dumps(self.to_dict())

    @property
    def network_string(self) -> str:
        """Returns a network string"""
        if self.port is None:
            return self.address
        return f"{self.address}:{self.port}"

    @property
    def is_local_host(self) -> bool:
        """Returns True if the address is localhost"""
        return self.address in ["localhost", "127.0.0.1"]


class DistributedSimulationProxyServer:
    """Class for handling distributed simulation proxy server"""

    def __init__(
            self,
            file_path_fmu: Optional[str] = None,
            endpoint: NetworkEndpoint = NetworkEndpoint(address="localhost", port=9090),
            source_text: Optional[str] = None,
    ):
        """Constructor for the class"""
        if source_text is not None:
            # source_text should be in the following form: "address:port?file=path/to/fmu"
            # if address is localhost, port may be missing
            address_port, query = source_text.split("?")
            address, port = address_port.split(":") if ":" in address_port else (address_port, None)
            port = int(port) if port is not None else None
            file_path_fmu = query.split("=")[1]
            endpoint = NetworkEndpoint(address=address, port=port)
        self.endpoint = endpoint
        self.file_path_fmu = file_path_fmu

    @property
    def _query_string(self):
        """Returns the query string for the endpoint"""
        return f"file={self.file_path_fmu}"

    @property
    def endpoint_str(self):
        """Returns the end point for a system structure file"""
        return f"proxyfmu://{self.endpoint.network_string}?{self._query_string}"


