
import {Action, Selector, State, StateContext} from '@ngxs/store';
import {tap} from 'rxjs/operators';
import {User} from "../model/user";
import {LoginService} from "../service/login.service";
import {Injectable} from "@angular/core";

export class LoginAction {
  static readonly type = '[Login Page] getUser';
  public username: string;
  public password: string;

  public constructor(username: string, password: string) {
    this.username = username;
    this.password = password;
  }
}
export class LogoutAction {
  static readonly type = '[Auth] Logout';
}
export interface IAuthUser {
  user?: User|null;
}
@State<IAuthUser>({
  name: 'USER_STATE',
  defaults:{user:null}
})
@Injectable()
export class UserState {


  @Selector()
  public static getRoles(state: IAuthUser) {
    if (state.user && state.user.roles) {
      return state.user.roles;
    }
    return null;
  }
  @Selector()
  public static getToken(state: IAuthUser) {
    if (state.user && state.user.token) {
      return state.user.token;
    }
    return null;
  }

  @Selector()
  public static userDetails(state: IAuthUser) {
    return state.user;
  }

  constructor(private loginApi: LoginService) {}


  @Action(LoginAction)
  // tslint:disable-next-line:typedef
  public signIn(ctx: StateContext<IAuthUser>, action: LoginAction) {
    let userLogged: any;
    try {
      return this.loginApi.login(action.username, action.password).pipe(tap((value) => {
        console.log(value)
        userLogged = value;
        ctx.patchState({user: userLogged});
      }));
    } catch (e) {
      ctx.patchState({user:null});
      return null;
      console.log(e);
    }
  }
  @Action([LogoutAction])
  public signOut(ctx: StateContext<IAuthUser>) {
    ctx.patchState({user: null});
  }

}
