import {ComponentExporterImporter} from "../ComponentExporterImporter";
import {TestableData} from "../../store";
import {CouponsPlus} from "../../../globals";

type WeeklyScheduleOptions = {
    timeSlots?: WeeklyScheduleTimeSlot[];
}

type WeeklyScheduleTimeSlot = {
    time?: {
        type?: 'hours' | 'range';
        value?: unknown[];
        __local?: {
            value_hours?: unknown[];
            value_range?: unknown[];
        }
    }
}

export class WeeklyScheduleExporterImporter implements ComponentExporterImporter<TestableData<WeeklyScheduleOptions>, TestableData<WeeklyScheduleOptions>> {
    type = CouponsPlus?.components?.conditions?.WeeklySchedule?.type || 'WeeklySchedule'

    importData(data: TestableData<WeeklyScheduleOptions>): TestableData<WeeklyScheduleOptions> {
        if (!Array.isArray(data?.options?.timeSlots)) {
            return data
        }

        data.options.timeSlots = data.options.timeSlots.map(timeSlot => {
            if (!timeSlot?.time || typeof timeSlot.time !== 'object') {
                return timeSlot
            }

            const localValues = timeSlot.time.__local || {}
            const currentValue = Array.isArray(timeSlot.time.value) ? timeSlot.time.value : []
            const localRange = this.getRangeValue(localValues.value_range)
            const valueRange = this.getRangeValue(currentValue)

            return {
                ...timeSlot,
                time: {
                    ...timeSlot.time,
                    __local: {
                        value_hours: Array.isArray(localValues.value_hours) ? localValues.value_hours : (
                            timeSlot.time.type === 'hours' ? currentValue : []
                        ),
                        value_range: localRange || (
                            timeSlot.time.type === 'range' ? (valueRange || ['00:00', '23:59']) : ['00:00', '23:59']
                        )
                    }
                }
            }
        })

        return data
    }

    private getRangeValue(value: unknown): [string, string] | undefined {
        if (!Array.isArray(value) || value.length < 2) {
            return undefined
        }

        return [value[0] as string, value[1] as string]
    }
}
