import { State, Store, Action, StateContext } from '@ngxs/store';
import * as actions from '../actions/branch-process.actions';
import { UserStateSyncData } from '../../models/user-state-sync.model';
import { AppUserDataSync } from '../actions/app.actions';
import { BranchProcess } from '../../models/branch-process.model';
import { PopLastBreadcrumbs } from '../actions/breadcrumb.actions';
import { FILIALE_LANDING_PAGE } from '../../utils/app.constants';
import { Injectable } from '@angular/core';

export class BranchProcessStateModel {
  branchProcess: BranchProcess;
}

@State<BranchProcessStateModel>({
  name: 'branchprocess',
  defaults: {
    branchProcess: { id: -1, currentRoute: undefined },
  },
})
@Injectable()
export class BranchProcessState {
  constructor(private store: Store) {}

  @Action(actions.SetBranchProcess)
  set(ctx: StateContext<BranchProcessStateModel>, { branchProcess }: actions.ReloadBranchProcess) {
    ctx.patchState({ branchProcess });
    this.syncApiState(branchProcess);
  }

  @Action(actions.SetBranchProcessCurrentPath)
  setCurrentPath(
    ctx: StateContext<BranchProcessStateModel>,
    { path, removeLastBreadcrumb, queryStrings }: actions.SetBranchProcessCurrentPath
  ) {
    const branchProcess = <BranchProcess>{ id: -1, currentRoute: path, currentRouteQueryParams: queryStrings };
    ctx.patchState({ branchProcess });
    if (removeLastBreadcrumb) {
      this.store.dispatch(new PopLastBreadcrumbs(path));
    }
    this.syncApiState(branchProcess);
  }

  @Action(actions.ReloadBranchProcess)
  reload(ctx: StateContext<BranchProcessStateModel>, { branchProcess }: actions.ReloadBranchProcess) {
    ctx.patchState({ branchProcess });
  }

  private syncApiState(branchProcess: BranchProcess) {
    const userSyncData: UserStateSyncData = {
      branchProcess,
    };
    const userData = JSON.stringify(userSyncData);
    this.store.dispatch(new AppUserDataSync(userData));
  }
}
