import numpy as np
from flatdict import FlatDict
from xml.etree import ElementTree as ET
from openpnm.io import GenericIO, Dict
from openpnm.utils import logging, Workspace
logger = logging.getLogger(__name__)
ws = Workspace()


class VTK(GenericIO):
    r"""
    The Visualization Toolkit (VTK) format defined by Kitware and used by
    Paraview.

    Notes
    -----
    Because OpenPNM data is unstructured, the actual output format is VTP,
    not VTK.

    """

    _TEMPLATE = """
    <?xml version="1.0" ?>
    <VTKFile byte_order="LittleEndian" type="PolyData" version="0.1">
        <PolyData>
            <Piece NumberOfLines="0" NumberOfPoints="0">
                <Points>
                </Points>
                <Lines>
                </Lines>
                <PointData>
                </PointData>
                <CellData>
                </CellData>
            </Piece>
        </PolyData>
    </VTKFile>
    """.strip()

    @classmethod
    def export_data(cls, network, phases=[], filename="", delim=" | ",
                    fill_nans=None, fill_infs=None):
        r"""
        Save network and phase data to a single vtp file for visualizing in
        Paraview.

        Parameters
        ----------
        network : GenericNetwork
            The Network containing the data to be written
        phases : list, optional
            A list containing GenericPhase(s) containing data to be
            written
        filename : str, optional
            Filename to write data.  If no name is given the file is named
            after the network
        delim : str
            Specify which character is used to delimit the data names.  The
            default is ' | ' which creates a nice clean output in the Paraview
            pipeline viewer (e.g. net | property | pore | diameter)
        fill_nans : scalar
            The value to use to replace NaNs with.  The VTK file format does
            not work with NaNs, so they must be dealt with.  The default is
            `None` which means property arrays with NaNs are not written to the
            file.  Other useful options might be 0 or -1, but the user must
            be aware that these are not real values, only place holders.
        fill_infs : scalar
            The value to use to replace infs with.  The default is ``None``
            which means that property arrays containing ``None`` will *not*
            be written to the file, and a warning will be issued.  A useful
            value is

        """
        project, network, phases = cls._parse_args(network=network, phases=phases)
        # Check if any of the phases has time series
        transient = GenericIO._is_transient(phases=phases)
        if transient:
            logger.warning(
                "vtp format does not support transient data, " + "use xdmf instead"