import {Action, Selector, State, StateContext} from "@ngxs/store";
import {Injectable} from "@angular/core";
import {
  FilterTimeTableAction, LoginAction,
} from "./app.actions";
import {TimeTableFilter} from "../app.types";
import jwtDecode, {JwtPayload} from "jwt-decode";

export interface Identity{
  username: string;
  card: string;
}
export interface AppStateModel {
  user: Identity
  token: string;
  filterTimeTable: FilterTimeTableAction;
}

@Injectable()
@State<AppStateModel>({
  name: "app",
  defaults: {
    user: null,
    token: null,
    filterTimeTable: {
      idTrainer: -1,
      idEventType: -1
    },
  },
})
export class AppState {


  constructor() {
  }

  @Selector()
  public static getFilterTimeTable(state: AppStateModel): TimeTableFilter {
    return state.filterTimeTable;
  }

  @Selector()
  public static getUser(state: AppStateModel): Identity {
    return state.user;
  }

  @Selector()
  public static getToken(state: AppStateModel): string {
    return state.token;
  }


  @Action(FilterTimeTableAction)
  dispatchFilterTimeTable(ctx: StateContext<AppStateModel>, {idEventType, idTrainer}: FilterTimeTableAction): void {
    ctx.patchState({
      filterTimeTable: {
        idEventType: idEventType,
        idTrainer: idTrainer
      }
    });
  }

  @Action(LoginAction)
  dispatchLogin(ctx: StateContext<AppStateModel>, {token}: LoginAction): void {
    let username = null;
    let card = null;

    try {
      const decoded = jwtDecode<JwtPayload & { username: string , card: string}>(token);
      username = decoded?.username;
      card = decoded?.card;
    } catch (e) {
      // user not logged in
      token = null;
      username = null;
      card = null;
    }


    ctx.patchState({
      user:  (username && card) ? {username: username, card: card } : null,
      token: token
    });
  }

}
