/** @module email/state */
import { call, put, takeEvery } from 'redux-saga/effects'
import { SZTM_API } from '../config/static'

/**
 * state.js
 *
 * Collection of everything which has to do with state changes.
 **/

/** actionTypes define what actions are handeled by the reducer. */
export const actions = {
  changeForm: (data) => {
    return {
      type: 'EMAIL/CHANGE_FORM',
      data
    }
  },
  setRecipients: (data) => {
    return {
      type: 'EMAIL/SET_RECIPIENTS',
      data
    }
  },
  addRecipient: (data) => {
    return {
      type: 'EMAIL/ADD_RECIPIENT',
      data
    }
  },
  sendEmailRequest: (data) => {
    return {
      type: 'EMAIL/SEND_REQUEST',
      data
    }
  },
  sendEmailSuccess: (data) => {
    return {
      type: 'EMAIL/SEND_SUCCESS',
      data
    }
  },
  sendEmailFailure: (error) => {
    return {
      type: 'EMAIL/SEND_FAILURE',
      error
    }
  }
}
console.log('State actions', actions)

/** state definition */
export const state = {
  recipients: [],
  sender: 'SZTM',
  body: '',
  sending: false,
  newRecipient: '',
  message: ''
}
console.log('State state', state)

/** reducer is called by the redux dispatcher and handles all component actions */
export function reducer (state = [], action) {
  switch (action.type) {
    case 'SMS/CHANGE_FORM':
      return { ...state, ...action.data }
    case 'SMS/SET_RECIPIENTS':
      return { ...state, recipients: action.data }
    case 'SMS/ADD_RECIPIENT':
      const number = normalizePhone(action.data)
      if (number) {
        return { ...state, recipients: [ number, ...state.recipients ], newRecipient: '' }
      } else {
        return state
      }      
    case 'SMS/SEND_REQUEST':
      return { ...state, sending: true }
    case 'SMS/SEND_SUCCESS':
      return { ...state, sending: false, message: action.data, recipients: [], newRecipient: '', body: '' }
    case 'SMS/SEND_FAILURE':
      return { ...state, sending: false, message: action.error }
    default:
      return state
  }
}

function * sendSMS (action) {
  try {
    const token = localStorage.getItem('accessToken')
    console.log('Send SMS requested', action, token)
    const { body, sender, recipients } = action.data
    const response = yield call(fetch, `${SZTM_API}/api/sms/send`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'x-access-token': token
      },
      body: JSON.stringify({
        recipients,
        body,
        sender
      })
    })
    if (response.status != 200) {
      console.log(response)
      throw Error(yield response.json())
    } else {
      const responseJson = yield response.json()
      yield put(actions.sendSMSSuccess(responseJson))
    }
  } catch (error) {
    console.log('Config failure!', actions.sendSMSFailure(error.toString()))
    yield put(actions.sendSMSFailure(error))
  }
}

/** sagas are asynchronous workers (JS generators) to handle the state. */
export function * saga () {
  console.log('SMS saga started.')
  yield takeEvery('SMS/SEND_REQUEST', sendSMS)
}
