import { cond, T, isEmpty } from "ramda";

const setPackColumns = (name) => {
  switch(name) {
  case 'КолонкиПакетов': 
    return [
      {
        title: "Пакет на проде",
        field: "switch ",
        width: 150,
        render: `
          <form x-data='{ isProd: {{ isProd }} }' phx-change='update_pack_struct_online:{{ id }}'>
            <div class='flex justify-center'>
              <div class='form-check form-switch'>
                <label for='toogle_group_{{ id }}' class='flex items-center cursor-pointer'>
                  <input value='true' x-model='isProd' id='toogle_group_{{ id }}' name='toogle_pack_struct_{{ id }}' class='form-check-input appearance-none w-9 rounded-full float-left h-3 align-top bg-white bg-no-repeat bg-contain bg-gray-300 checked:bg-blue-500 focus:outline-none cursor-pointer shadow-sm' type='checkbox' role='switch' id='flexSwitchCheckDefault'>
                </label>
              </div>
            </div>
          </form>
          `
      },
      {
        title: "Название",
        field: "name",
        width: 180
      },
      {
        title: "Действия",
        field: "actions",
        width: 100,
        render: `
          <div class='flex gap-2 py-1'>
            <button style='width: 25px; height: 25px;' class='italic border border-solid transition-all duration-300 rounded-full cursor-pointer hover:text-gray-500 linear-loader card-btn-action pt-[2px] text-primary' phx-click='select_struct:{{ id }}' >
              <i class='ri-eye-fill'></i>
            </button>
            <button style='width: 25px; height: 25px;' class='italic border border-solid transition-all duration-300 rounded-full cursor-pointer hover:text-gray-500 linear-loader card-btn-action'>
              <i class='ri-pencil-fill'></i>
            </button>
            <button style='width: 25px; height: 25px;' class='relative flex items-center justify-center italic border border-solid transition-all duration-300 rounded-full cursor-pointer hover:text-gray-500 linear-loader card-btn-action-red' x-data='{ open: false }' @click='open = !open'>
                <div x-show='open' class='popup-text not-italic'>
                  <span>Вы точно хотите удалить структуру?</span>
                  <span class='flex gap-2'>
                    <span class='justify-center flex flex-grow bg-blue-500 hover:bg-blue-700 text-white rounded'>Да</span>
                    <span class='justify-center flex flex-grow bg-gray-500 hover:bg-gray-700 text-white rounded'>Отмена</span>
                  </span>
                </div>
                <i class='ri-delete-bin-fill'></i>
                </button>
          </div>
          `
      }
    ]
  case 'Сырые': 
    return [
      {
        title: "Время пакета",
        field: "pack_dt",
        width: 180
      },
      {
        title: "Архивная дата",
        field: "arhiv_date",
        width: 90
      },
      {
        title: "Номер пакета",
        field: "pack_number",
        width: 70
      },
      {
        title: "Длинна пакета",
        field: "pack_len",
        width: 70
      },
      {
        title: "Репл",
        field: "id_repl",
        width: 70
      },
      {
        title: "IMEI",
        field: "imei",
        width: 120
      },
      {
        title: "ДАННЫЕ",
        field: "data",
        width: 600
      },
      {
        title: "Дата начала передачи",
        field: "connect_dt",
        width: 180
      },
      {
        title: "Дата завершения передачи",
        field: "disconnect_dt",
        width: 180
      }
    ]
  case 'Нераспознанные':
    return [
      {
        title: "Время пакета",
        field: "pack_dt",
        width: 180
      },
      {
        title: "Архивная дата",
        field: "arhiv_date",
        width: 90
      },
      {
        title: "Номер пакета",
        field: "pack_number",
        width: 70
      },
      {
        title: "Длинна пакета",
        field: "pack_len",
        width: 70
      },
      {
        title: "Репл",
        field: "id_repl",
        width: 70
      },
      {
        title: "IMEI",
        field: "imei",
        width: 120
      },
      {
        title: "ДАННЫЕ",
        field: "data",
        width: 600
      },
      {
        title: "Дата начала передачи",
        field: "connect_dt",
        width: 180
      },
      {
        title: "Дата завершения передачи",
        field: "disconnect_dt",
        width: 180
      }
    ]
  default: return []
  }
}

const prepareSetPackColumns = (name, data) => {
  console.log('prepareSetPackColumns data', data);
  console.log('prepareSetPackColumns name', name);
  switch(name) {
  case 'askr_logs': 
    if (data.length > 0) {
      return data[0].map((el) => ({title: Object.keys(el)[0], field: Object.keys(el)[0], width: 150}))
    }
    if (data.length === 0) {
      return []
    }
    break  
  case 'raw':
    return setPackColumns('Сырые')
  case 'unrecognized':
    return setPackColumns('Нераспознанные')
  default: return []
  }
}

const normalizeCols = (cols) => {
  console.log('normalizeCols - cols', cols)
  const withoutCoordsPackDtCols = cols.filter((el) => el.field !== 'pack_dt' && el.field !== 'lat_lon')
  const coordsField = {
    title: "Координаты",
    field: "lat_lon",
    key: "coords",
    render: `(_, rec) => {
      if (!rec?.geo) return ""
      const lat = rec?.geo?.coordinates[1]
      const lon = rec?.geo?.coordinates[0]
      return \`<div class="underline underline-offset-2 decoration-dashed cursor-pointer" phx-click="load_map" phx-value-lon="\${lat}" phx-value-lat="\${lon}">
          \${lat ? +lat.toFixed(5) : lat} \${lon ? +lon.toFixed(5) : lon}
        </div>\`
    }`
  }
  const packDtField = {
    title: "Дата формирования пакета",
    field: "pack_dt",
    key: "pack_dt",
    render: `{{ dt_format (dt_shift pack_dt 3 'hour') }}`,
    width: 130
  }
  return [packDtField, coordsField, ...withoutCoordsPackDtCols]
}

const parseCols = (packStructure, report) => {
  if (!isEmpty(packStructure)) return normalizeCols(packStructure)
  if (!packStructure && report && !isEmpty(report)) return prepareSetPackColumns('askr_logs', report.askr_logs)
  if (!packStructure && !report) return []
}

const fetchColumn = (packStructure, report, id = null) => {
  console.log('packStructure', packStructure)
  console.log('id', id)
  const getCurrentPackColls = (packStructure, id) => {
    const currentPackStructure = packStructure.find((el) => el.id === id)
    console.log('currentPackStructure', currentPackStructure)
    const currColumns = currentPackStructure.columns ? currentPackStructure.columns : []
    return parseCols(currColumns, null)
  }
  return cond([
    [(packStructure) => !packStructure === true,  () => parseCols(null, report)],
    [(packStructure) => (packStructure?.length >= 1) && (id && typeof id === 'number'),  () => getCurrentPackColls(packStructure, id)],
    [(packStructure) => packStructure?.length >= 1,  () => parseCols(packStructure[0].columns, null)],
    [T, () => parseCols(null, report)],
  ])(packStructure)
}

export {prepareSetPackColumns, setPackColumns, normalizeCols, parseCols, fetchColumn}