import { useState, useEffect } from 'react'
import moment from 'moment'
import { EditableTable, DatePickerWrapper } from '../../components/Table'
import LoaderPortal from '../../components/LoaderPortal'
import { invokeWebApiWrapperAsync } from '../../components/factory'
import { MeasureService } from '../../services/api'

const format='YYYY.MM.DD HH:mm'

const columnTimestamp = {
  editable: true,
  title: 'Время',
  key:'timestamp',
  dataindex:'timestamp',
  input: <DatePickerWrapper/>,
  width:'12em',
  render: (text, record, idx) => record['timestamp'],
}

export const Editor = ({idWell, idCategory, columns, onUpdate}) => {
  const [showLoader, setShowLoader] = useState(false)
  const [history, setHistory] = useState([])

  const update = () => invokeWebApiWrapperAsync(async()=>{
    const data = await MeasureService.getHisory(idWell, idCategory)
    const story = data?.map( i=> ({
      id: i.id,
      idWell: i.idWell,
      idCategory: i.idCategory,
      timestamp: moment.utc(i.timestamp).local().format(format),
      ...i.data}))
    setHistory(story??[])
  }
  , setShowLoader
  , "не удалось загрузить")

  useEffect(update, [idWell, idCategory])

  const onAdd = async (row) => {
    const {id, idCategory: _idCategory, idWell : _idWell, timestamp, key, ...data} = row
    const measure = {
      id:0,
      idWell: idWell,
      idCategory: idCategory,
      timestamp: timestamp?? moment(),
      data,
    }
    await MeasureService.insert(idWell, measure)    
    if(onUpdate)
      onUpdate()
    else
      update()
  }

  const onEdit = async (row) => {
    if(!row?.id)
      return
    const {id, idCategory: _idCategory, idWell : _idWell, timestamp, ...data} = row
    const measure = {
      id: id,
      idWell: idWell,
      idCategory: idCategory,
      timestamp: moment(timestamp)?? moment(),
      data,
    }
    try{
      await MeasureService.update(idWell, measure)
    }
    catch(ex){
      console.write(ex)
    }
    if(onUpdate)
      onUpdate()
    else
      update()
  }

  const onDelete = async (row) => {
    if(!row?.id)
      return
    await MeasureService.markAsDelete(idWell, row.id)
    if(onUpdate)
      onUpdate()
    else
      update()
  }

  return <LoaderPortal show={showLoader}>
    <EditableTable
      bordered
      dataSource = {history}
      columns = {[columnTimestamp,...columns]}
      onRowAdd = {onAdd}
      onRowEdit = {onEdit}
      onRowDelete = {onDelete}
      size = 'small'
      scroll={{ x: 400, y: 600 }}
    />
  </LoaderPortal>
}