import {getFormValues, actions as formActions, isValid} from 'redux-form'
import {CHANGE, UPDATE_SYNC_ERRORS, INITIALIZE} from 'redux-form/es/actionTypes'
import {externalEvents, form as formUtil} from 'tocco-app-extensions'
import {all, call, put, select, takeEvery, takeLatest} from 'redux-saga/effects'

import * as actions from './actions'

const FORM_ID = 'simpleForm'
export const inputSelector = state => state.input
export const selector = state => state.simpleForm

export default function* sagas() {
  yield all([
    takeEvery(actions.INITIALIZE_QUESTION_FORM, initialize),
    takeEvery(actions.SUBMIT, submit),
    takeEvery(actions.CANCEL, cancel),
    takeLatest(CHANGE, change),
    takeLatest(UPDATE_SYNC_ERRORS, change),
    takeLatest(INITIALIZE, change)
  ])
}

export function* initialize() {
  const {form} = yield select(inputSelector)
  const fieldDefinitions = yield call(formUtil.getFieldDefinitions, form)
  const defaultValues = yield call(formUtil.getDefaultValues, fieldDefinitions)
  yield put(formActions.initialize(FORM_ID, defaultValues))
}

export function* submit() {
  const values = yield select(getFormValues(FORM_ID))
  yield put(externalEvents.fireExternalEvent('onSubmit', {values}))
}

export function* cancel() {
  const values = yield select(getFormValues(FORM_ID))
  yield put(externalEvents.fireExternalEvent('onCancel', {values}))
}

export function* change() {
  const values = yield select(getFormValues(FORM_ID))
  const valid = yield select(isValid(FORM_ID))
  yield put(externalEvents.fireExternalEvent('onChange', {values, valid}))
}

@@ -1124,37 +1124,18 @@
 eld 
-select(getFormValues(FORM_ID)
+getValues(
 )%0A  
@@ -1258,37 +1258,18 @@
 eld 
-select(getFormValues(FORM_ID)
+getValues(
 )%0A  
@@ -1392,37 +1392,18 @@
 eld 
-select(getFormValues(FORM_ID)
+getValues(
 )%0A  
@@ -1520,12 +1520,228 @@
  valid%7D))%0A%7D%0A
+%0Afunction* getValues() %7B%0A  return Object.entries(yield select(getFormValues(FORM_ID)))%0A    .reduce((acc, %5Bkey, value%5D) =%3E %7B%0A      return %7B%0A        ...acc,%0A        %5Bkey.replace('--', '.')%5D: value%0A      %7D%0A    %7D, %7B%7D)%0A%7D%0A

use real paths when firing external events