import { HttpRequest } from '@angular/common/http';
import { MatDialogRef } from '@angular/material/dialog';
import { AuthActions, SET_TOKEN, SET_USER, INIT_LOGIN_DIALOG, CLOSE_LOGIN_DIALOG, SET_USERS, SET_LOGIN_TIMEOUT, SIGN_OFF, REMOVE_LOGIN_TIMEOUT, SIMPLE_SIGN_OFF } from './auth.actions';
import { User } from '../../core/model/user.model';
import { LoginDialogComponent } from '../login/login-dialog/login-dialog.component';
import { JwtUtil } from 'src/app/shared/jwt.util';
import { JwtBody } from 'src/app/model/jwtBody';

export interface AuthState{
    token: string,
    user: User;
    loginDialogReference: MatDialogRef<LoginDialogComponent>;
    loginTimeout: number;
    users: User[];
}

const initialState: AuthState = {
    token: null,
    user: null,
    loginDialogReference: null,
    loginTimeout: null,
    users: null
}

export function authReducers(state = initialState, action: AuthActions){
    switch(action.type){
        case SET_TOKEN:
            return {
                ...state,
                token: action.payload
            };
        case SET_USER:
            return {
                ...state,
                user: action.payload
            };
        case INIT_LOGIN_DIALOG:
            return {
                ...state,
                loginDialogReference: action.loginDialogReference,
            }
        case CLOSE_LOGIN_DIALOG:
            return {
                ...state,
                loginDialogReference: initialState.loginDialogReference,
            }
        case SET_LOGIN_TIMEOUT:
            return {
                ...state,
                loginTimeout: action.loginTimeout
            }
        case REMOVE_LOGIN_TIMEOUT:
            clearTimeout(state.loginTimeout);
            return {
                ...state,
                loginTimeout: null
            }
        case SET_USERS:
            return {
                ...state,
                users: action.users
            }
        case SIMPLE_SIGN_OFF:
            return {
                ...state,
                token: initialState.token,
                user: initialState.user,
                users: initialState.users,
            }
        default:
            return state;
    }
}