#! /usr/bin/env python
# filename: tops_ptopo.py
# Copyright 2022 Jean-Marie Arsac <jmarsac@azimut.fr>
#
# This file is part of Total Open Station.
#
# Total Open Station is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# Total Open Station is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty
# of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Total Open Station.  If not, see
# <http://www.gnu.org/licenses/>.

import io

from ...ptopo import Ptopo
from . import Builder


class OutputFormat(Builder):

    """
    Exports points data in ptopo array

    ``data`` should be an iterable containing Feature objects.
    """

    def __init__(self, data):
        self.data = data
        self.output = io.StringIO()
        fieldnames = [
            "type",
            "matricule",
            "x",
            "y",
            "z",
            "prec_xy",
            "prec_z",
            "code",
            "infos",
        ]

    def process(self):
        ptopo_array = []
        for feature in self.data:
            row = {
                "type": feature.desc,
            }

            props = {
                "point_name": "matricule",
                "prec_xy": "prec_xy",
                "prec_z": "prec_z",
                "attrib": "infos",
                "code": "code",
            }
            for prop in props.keys():
                row[props[prop]] = feature.properties.get(
                    prop, "?"
                )  # interrogation string as default value

            ptopo = self.to_ptopo(feature.geometry, row)
            if ptopo:
                ptopo_array.append(ptopo)

        return ptopo_array

    def to_ptopo(self, pt, row):
        ptopo = None
        if "matricule" in row and "prec_xy" in row and "prec_z" in row:
            ptopo = Ptopo(
                row["matricule"],
                row["type"],
                pt.x,
                pt.y,
                pt.z,
                None,
                row["prec_xy"],
                row["prec_z"],
            )
            if "code" in row:
                if row["code"] and row["code"] != "?":
                    ptopo.codes = row["code"]
        return ptopo
