import io
import typing
from collections import OrderedDict

try:
    import pandas as pd
except ImportError:
    from ..stubs import pandas as pd

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 FlatV(Weir):

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

    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.
        return d

    def get_xs(self) -> Output:
        self.xs = super().get_xs()
        x = [0., self.unit.b / 2., self.unit.b]
        h = self.unit.b / 2 / self.unit.m
        y = [self.unit.zc + h, self.unit.zc, self.unit.zc + h]
        df = pd.DataFrame(list(zip(x, y)), columns=['x', 'y'])
        buf = io.StringIO()
        buf.write(f'! Generated by fm_to_estry. Source: {self.dat.name}/{self.unit.uid}\n')
        df.to_csv(buf, index=False, lineterminator='\n')
        self.xs.content = buf.getvalue()
        return self.xs
