import { Component, OnInit } from '@angular/core';
import { ComponentBase } from '@core/base/common-base';
import { AuthService } from '@core/services/authentication/auth.service';
import { ADD_PROFILE } from '@core/state/profile/profile.actions';
import { takeUntil } from 'rxjs';
import { Store } from '@ngrx/store';
import { USER } from '@core/models/authenticcation.model';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent extends ComponentBase implements OnInit {
  title = 'mt-works';
  constructor(
    private readonly authService: AuthService,
    private readonly store: Store<{ user: { profile: USER } }>
  ) {
    super();
  }

  ngOnInit(): void {
    if (this.authService.isAuthenticated()) {
      this.getProfile();
    }
  }

  getProfile(): void {
    this.authService
      .getUserData()
      .pipe(takeUntil(this.destroy$))
      .subscribe((res) => {
        this.store.dispatch(
          ADD_PROFILE({
            user: { userName: res.userName, email: res.email },
          })
        );
      });
  }
}
