import { State, Action, StateContext, Store } from '@ngxs/store';
import * as actions from '../actions/branch.actions';
import { tap } from 'rxjs/operators';
import { CheckoutService } from '../../services/checkout.service';
import { BranchDTO } from '@swagger/checkout';
import { SsoService } from 'sso';
import { Injectable } from '@angular/core';

export class BranchesStateModel {
  branches: { [key: number]: BranchDTO };
  userBranch: string;
}

@State<BranchesStateModel>({
  name: 'branches',
  defaults: {
    branches: {},
    userBranch: undefined,
  },
})
@Injectable()
export class BranchState {
  constructor(private branchService: CheckoutService, private ssoService: SsoService, private store: Store) {}

  @Action(actions.LoadBranches)
  loadBranches(ctx: StateContext<BranchesStateModel>) {
    return this.branchService.getBranches().pipe(
      tap((branchData: BranchDTO[]) => {
        if (branchData.length > 0) {
          const state = ctx.getState();
          const branches = { ...state.branches };

          branchData.forEach((branch: BranchDTO) => {
            branches[branch.id] = branch;
          });

          ctx.patchState({
            ...state,
            branches: branches,
          });
        }
      })
    );
  }

  @Action(actions.LoadUserBranch)
  loadUserBranch(ctx: StateContext<BranchesStateModel>) {
    const userBranch: string = this.ssoService.getClaimByKey('branch_no');
    ctx.patchState({ userBranch });
  }

  @Action(actions.AddBranchesIfNotLoaded)
  addBranchesIfNotLoaded(ctx: StateContext<BranchesStateModel>, { payload }: actions.AddBranchesIfNotLoaded) {
    const state = ctx.getState();
    if (!state) {
      return;
    }
    if (payload && payload.length > 0) {
      const branches = { ...state.branches };
      payload.forEach((branch) => {
        const branchExists = branches[branch.id];
        if (!branchExists) {
          branches[branch.id] = branch;
        }
      });

      ctx.patchState({
        branches: branches,
      });
    }
  }
}
