import { EditorProperty } from "@iplusplus/y-model"
import { CellRender, CellRenderBuilder2 } from "../../types"
import { KeyValueItem } from "./types"
import { CellEnumSelectList } from "./CellEnumSelectList"

function parseKeyValueString(str: string): KeyValueItem[] {
  if (str === "") return []
  return str
    .split(";")
    .filter(s => s.indexOf("=") > 0)
    .map(s => {
      const idx = s.indexOf("=")
      return [s.substring(0, idx), s.substring(idx + 1)]
    })
}

export function renderEnumSelectCell(items: KeyValueItem[]): CellRender {
  return params => {
    return <CellEnumSelectList items={items} params={params} />
  }
}

export function renderEnumCell(items: KeyValueItem[]): CellRender {
  return params => {
    const r = items.find(item => item[0] == params.value || (params.value===undefined && item[0]==="undefined"))
    return <div> {r ? r[1] : params.value}</div>
  }
}

export const enumRenderBuilder: CellRenderBuilder2 = (property: EditorProperty) => {
  if (property.editorType.startsWith("enum:")) {
    const items = parseKeyValueString(property.editorType.substring(5))

    return {
      editorCellRender: renderEnumSelectCell(items),
      cellRender: renderEnumCell(items),
    }
  }
  return undefined
}
