import {isEmpty} from 'ramda'
import {searchModes} from './StaticData'

const prepareSelects = (selects, selectors) => {
  const updatedSelects = selects.reduce((acc, el) => {
    if (selectors[el.key]) {
      const newEl = {...el, data: selectors[el.key]}
      acc = [...acc, newEl]
    } else {
      acc 
    }
    return acc
  }, [])
  // console.log('updSelects', updatedSelects)
  
  const filteredSelects = updatedSelects.map((el) => ({...el, data: el.data.reduce((acc, select) => {
    if (select) {
      const newSelect = {name: select}
      acc = [...acc, newSelect]
    } else {
      acc
    }
    return acc
  }, [])
  })).sort((a, b) => a.order - b.order)
  // console.log('filteredSelects', filteredSelects)
  return filteredSelects
}

const mergedMachines = (machinesData, historyData) => {
  const orderHistoryData = historyData.map((el, idx) => ({...el, order: idx}))
  const historyMachinesIds = orderHistoryData.filter((el, idx, arr) => arr.findIndex((item) => item.machine_id === el.machine_id) === idx).map((el) => el.machine_id)
  const historyMachines = Array.from(machinesData).filter((el) => historyMachinesIds.find((id) => id === el.machine_id)).sort((a, b) => a.order - b.order)
  const countHistoryNachines = historyMachines.length > 0 ? historyMachines.slice(0, 20).length : 0
  const currentMachines = machinesData.slice(0, 20 - countHistoryNachines)
  return [...historyMachines.slice(0, 20), ...currentMachines]
}

const colorSelection = (key, value) => {
  if(key) {
    const machinesContainer = document.querySelector('#listMachines')
    const allSearchField = machinesContainer ? machinesContainer.querySelectorAll('[search-mode]') : null
    if (allSearchField) {
      allSearchField.forEach((el) => {
        el.style = ''
      })
    }
    if (value) {
      const searchField = machinesContainer ? machinesContainer.querySelectorAll(`[search-mode=${key}]`) : null
      if (searchField) {
        searchField.forEach((el) => {
          el.style.width = "fit-content"
          el.style.padding = "2px"
          // el.style.color = "#FFF"
          el.style.borderRadius = "3px"
          el.style.backgroundColor = "rgb(1 97 253 / 30%)"
        })
      }
    }
  }
}

const findMachine = (machine, filters) => {
  const isArr = filters && Array.isArray(filters)
  if (isArr) {
    const filteredMachine = filters.filter((filter) => {
      if (machine === filter) {
        return machine
      }
    })
    return filteredMachine.length > 0 ? true : false
  }
  if (!isArr) {
    if (`${machine}`.includes(filters)) { // Для поиска неточное совпадение
      return true
    }
    return false
  }
}

const setUpdatedDataMachines = (machines, params) => {
  const filters = params.filter
  if(!isEmpty(filters)) {
    const searchModeKeys = searchModes.map((el) => el.key)
    const searchData = filters.find((filter) => (searchModeKeys.includes(Object.entries(filter)[0][0])))
    const currentFilters = searchData ? [searchData] : filters
    const filteredMachines = machines.filter((machine) => {
      return currentFilters.find((filter) => {
        const entries = Object.entries(filter)
        if (!isEmpty(entries) && machine[entries[0][0]] && findMachine(machine[entries[0][0]], entries[0][1])) {
          return machine
        }
      })
    })
    // console.log('filteredMachines', filteredMachines)
    return filteredMachines
  }
  return machines
}

const loadingPagination = (machines, pagination) => {
  pagination.paginationOptions.total = machines.length
  pagination.paginationOptions.total_pages = Math.ceil(pagination.paginationOptions.total / pagination.paginationOptions.page_size)
  return machines.slice(0, pagination.paginationOptions.page_size)
}

const setPagination = (machines, pagination, updatedData) => {
  const pageNumber = Number(updatedData.pageNumber)
  const pageSize = Number(updatedData.pageSize)
  pagination.paginationOptions.total_pages = Math.ceil(pagination.paginationOptions.total / pageSize)
  const updatedPaginationOptions = {...pagination.paginationOptions, page_number: pageNumber, page_size: pageSize}
  const updatedPagination = {...pagination, paginationOptions: updatedPaginationOptions}
  const beginPageDataIdx = pageSize === 1 ? 0 : (pageNumber - 1) * pageSize
  const endPageDataIdx = beginPageDataIdx + pageSize
  const isEndPageDataIdxMore = endPageDataIdx > machines.length
  const currentTableData = isEndPageDataIdxMore ? machines.slice(beginPageDataIdx) : machines.slice(beginPageDataIdx, endPageDataIdx)
  return {currentTableData, updatedPagination}
}

export { prepareSelects, mergedMachines, colorSelection, setUpdatedDataMachines, loadingPagination, setPagination }