import { State, Action, StateContext, Store, Selector } from '@ngxs/store';
import { SaveFormState, DeleteFormState, ReloadFormState } from '../actions/forms.actions';
import { AppState } from './app.state';
import { UserStateSyncData } from '../../models/user-state-sync.model';
import { AppUserDataSync } from '../actions/app.actions';
import { Injectable } from '@angular/core';

export interface FormsStateModel {
  form: { [id: number]: { [key: string]: string } };
}

@State<FormsStateModel>({
  name: 'forms',
  defaults: {
    form: [],
  },
})
@Injectable()
export class FormsState {
  constructor(private store: Store) {}

  @Action(SaveFormState)
  saveFormState(ctx: StateContext<FormsStateModel>, { key, form }: SaveFormState) {
    const state = ctx.getState();
    const processId = this.store.selectSnapshot(AppState.getCurrentProcessId);
    const currentFormState = state.form;
    const updatedFormState = { ...currentFormState, [processId]: { ...currentFormState[processId], [key]: form } };
    ctx.setState({ form: updatedFormState });
    this.syncApiState(updatedFormState);
  }

  @Action(DeleteFormState)
  deleteFormState(ctx: StateContext<FormsStateModel>, { key }: DeleteFormState) {
    const state = ctx.getState();
    const processId = this.store.selectSnapshot(AppState.getCurrentProcessId);
    const currentFormState = state.form;
    const updatedFormState = { ...currentFormState, [processId]: { ...currentFormState[processId], [key]: undefined } };
    ctx.setState({ form: updatedFormState });
    this.syncApiState(updatedFormState);
  }

  @Action(ReloadFormState)
  reloadFormState(ctx: StateContext<FormsStateModel>, { formsState }: ReloadFormState) {
    ctx.setState({ form: formsState });
  }

  private syncApiState(formsState: { [id: number]: { [key: string]: string } }) {
    const userSyncData: UserStateSyncData = {
      formsState,
    };
    const userData = JSON.stringify(userSyncData);
    this.store.dispatch(new AppUserDataSync(userData));
  }
}
