from src.config.objects import TargetObject
from src.converter.convert_strategy import ConvertStrategyFactory


class CSVStringConverter:
    def __init__(self, target_object: TargetObject, sf_object_jsons: dict) -> None:
        self.__target_object = target_object
        # メモリ節約のため、ジェネレータ化
        self.__sf_object_jsons = (i for i in sf_object_jsons)
        self.__convert_strategy_factory = ConvertStrategyFactory()

    def convert(self) -> str:
        csv_data = self.__convert_to_csv(self.__sf_object_jsons)
        return csv_data

    def __extract_necessary_props_from(self, sf_object_json) -> dict:
        del sf_object_json['attributes']
        return {k.upper(): v for k, v in sf_object_json.items()}

    def __convert_to_csv(self, sf_object_jsons) -> list:
        try:
            columns = self.__target_object.columns
            csv_data = [columns]
            for i, json_object in enumerate(sf_object_jsons, 1):
                json_object = self.__extract_necessary_props_from(json_object)
                csv_row = []
                for column in columns:
                    v = json_object[column.upper()]

                    convert_strategy = self.__convert_strategy_factory.create(v)
                    converted_value = convert_strategy.convert_value(v)

                    csv_row.append(converted_value)

                csv_data.append(csv_row)
            return csv_data

        except Exception as e:
            raise Exception(
                f'CSV変換に失敗しました カラム名：[{column}] 行番号: [{i}] エラー内容:[{e}]')
