import { Action } from 'redux' import { setEntities } from '../actions/entities' import { startRequest, finishRequest } from '../actions/requests' import { apiFetch } from '../api' import { normalize } from '../utils/normalization' import { AppThunkAction, Installation, RequestKey, EntityType, Settings } from '../types' export interface SetInstallationsAction extends Action { type: 'COMPOSER_SET_INSTALLATIONS' payload: string[] } export interface SetSelectedInstallationAction extends Action { type: 'COMPOSER_SET_SELECTED_INSTALLATION' payload?: string } export interface SetHeightAction extends Action { type: 'COMPOSER_SET_HEIGHT', payload: number } export interface SetErrorAction extends Action { type: 'COMPOSER_SET_ERROR', payload?: string } export type ComposerActions = SetInstallationsAction | SetSelectedInstallationAction | SetHeightAction | SetErrorAction export const setInstallations = (installations: string[]): SetInstallationsAction => ({ type: 'COMPOSER_SET_INSTALLATIONS', payload: installations, }) export const setSelectedInstallation = (installation?: string): SetSelectedInstallationAction => ({ type: 'COMPOSER_SET_SELECTED_INSTALLATION', payload: installation, }) export const setHeight = (height: number): SetHeightAction => ({ type: 'COMPOSER_SET_HEIGHT', payload: height, }) export const setError = (error?: string): SetErrorAction => ({ type: 'COMPOSER_SET_ERROR', payload: error, }) interface FetchInstallationsResponse { installations: Installation[] } export const fetchInstallations = (): AppThunkAction => async dispatch => { dispatch(startRequest(RequestKey.FetchInstallations)) try { const response = await apiFetch({ path: '/v1/installations', }) const result = normalize(response.installations, EntityType.Installation) dispatch(setEntities(result.entities)) dispatch(setInstallations(result.keys)) dispatch(finishRequest(RequestKey.FetchInstallations, true)) } catch (err) { dispatch(finishRequest(RequestKey.FetchInstallations, false)) throw err } } export const saveInstallationSettings = (id: string, settings: Settings): AppThunkAction => async dispatch => { dispatch(startRequest(RequestKey.UpdateInstallationSettings)) try { await apiFetch({ path: `/v1/installation/${id}/settings`, method: 'put', body: { settings }, }) dispatch(finishRequest(RequestKey.UpdateInstallationSettings, true)) } catch (err) { dispatch(finishRequest(RequestKey.UpdateInstallationSettings, false)) throw err } }