// @flow
import { toPath } from 'lodash'
import type { Structure } from './types'

type ShouldDelete<SDM, SDL> = (
  structure: Structure<SDM, SDL>
) => (state: SDM | SDL, path: string) => boolean

function createCreateDeleteInWithCleanUp<DIM, DIL>(
  structure: Structure<DIM, DIL>
) {
  const shouldDeleteDefault: ShouldDelete<DIM, DIL> = structure => (
    state,
    path
  ) => structure.getIn(state, path) !== undefined

  const { deepEqual, empty, getIn, deleteIn, setIn } = structure

  return (
    shouldDelete: ShouldDelete<DIM, DIL> = shouldDeleteDefault
  ): DIM | DIL => {
    const deleteInWithCleanUp = (state: DIM | DIL, path: string): DIM | DIL => {
      if (path[path.length - 1] === ']') {
        // array path
        const pathTokens = toPath(path)
        pathTokens.pop()
        if(getIn(state, pathTokens.join('.'))) {
          setIn(state, path)
        }
      }

      let result: DIM | DIL = state

      if (shouldDelete(structure)(state, path)) {
        result = deleteIn(state, path)
      }

      const dotIndex = path.lastIndexOf('.')
      if (dotIndex > 0) {
        const parentPath = path.substring(0, dotIndex)
        const parent = getIn(result, parentPath)
        return deleteInWithCleanUp(result, parentPath)
      }
      return result
    }

    return deleteInWithCleanUp
  }
}

export default createCreateDeleteInWithCleanUp

@@ -803,11 +803,23 @@
     
-if(
+const parent = 
 getI
@@ -848,19 +848,16 @@
 in('.'))
-) %7B
 %0A       
@@ -857,17 +857,31 @@
         
- 
+return parent ?
  setIn(s
@@ -895,18 +895,16 @@
 ath)
-%0A        %7D
+ : state
 %0A   
@@ -1170,16 +1170,75 @@
 tIndex)%0A
+        if (parentPath%5BparentPath.length - 1%5D !== '%5D') %7B%0A  
         
@@ -1274,24 +1274,70 @@
 parentPath)%0A
+          if (deepEqual(parent, empty)) %7B%0A    
         retu
@@ -1375,24 +1375,46 @@
 parentPath)%0A
+          %7D%0A        %7D%0A
       %7D%0A    

Revert "Fix clear errors in parent of array after child change (#4014)" (#4049)