import io
import typing
from collections import OrderedDict

from fm_to_estry.converters.weir import Weir
from fm_to_estry.output import Output


if typing.TYPE_CHECKING:
    from fm_to_estry.parsers.units.handler import Handler


class Spill(Weir):

    @staticmethod
    def complete_unit_type_name() -> str:
        return 'SPILL_'

    def has_xs(self) -> bool:
        return True

    def map_nwk_attributes(self, field_map: dict, unit: 'Handler') -> OrderedDict:
        d = super().map_nwk_attributes(field_map, unit)
        d['Type'] = 'WW'
        d['US_Invert'] = -99999.
        d['DS_Invert'] = -99999.
        d['Height_or_WF'] = 1.
        d['HConF_or_WC'] = self.unit.cd
        return d

    def get_xs(self) -> Output:
        self.xs = super().get_qh()
        section = self.unit.xs.rename(columns={'Chainage': 'x', 'Elevation': 'y'})
        buf = io.StringIO()
        buf.write(f'! Generated by fm_to_estry. Source: {self.dat.name}/{self.unit.uid}\n')
        section.to_csv(buf, index=False, lineterminator='\n')
        self.xs.content = buf.getvalue()
        return self.xs
