import { DialogService } from './../../core/dialog.service';
import { RequestUsersAction, RequestDeleteOtherUserAction, RequestUserAction, RequestApproveUsersAction, RequestRejectUsersAction } from './../store/auth.actions';
import { AuthState } from 'src/app/auth/store/auth.reducers';
import { AppState } from './../../store/app.reducers';
import { Store } from '@ngrx/store';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { Router } from '@angular/router';
import { User } from 'src/app/core/model/user.model';

@Component({
  selector: 'app-profiles',
  templateUrl: './profiles.component.html',
  styleUrls: ['./profiles.component.scss']
})
export class ProfilesComponent implements OnInit, OnDestroy {

  private storeSubscription: Subscription;

  private loggedUser: User;

  public inactiveUsers: User[];
  public users: User[];

  private userId: number = null;
  
  constructor(private store: Store<AppState>, private dialogService: DialogService, private router: Router) { }

  ngOnInit() {
    this.storeSubscription = this.store.select('authState').subscribe(
      (state: AuthState) => {
        if (state.user === null)
          this.store.dispatch(new RequestUserAction());
      
        this.loggedUser = state.user;

        let inactiveUsers: User[] = state.users === null ? null : state.users.filter((user: User) => { return user.active ? null : user});
        let activeUsers: User[] = state.users === null ? null : state.users.filter((user: User) => { return user.active ? user : null});

        this.inactiveUsers = inactiveUsers === null || inactiveUsers.length < 1 ? null : inactiveUsers;
        this.users = activeUsers === null || activeUsers.length < 1 ? null : activeUsers;
      }
    );

    this.store.dispatch(new RequestUsersAction());
  }

  onApproveAll(){
    this.dialogService.confirm('Schválit vše ?', 'Opravdu si přejete schválit všechny neschválené profily ?').subscribe(result => {
      if (result)
        this.store.dispatch(new RequestApproveUsersAction(this.inactiveUsers));
    });
  }

  onRejectAll(){
    this.dialogService.confirm('Zamítnout vše ?', 'Opravdu si přejete zamítnouts všechny neschválené profily ?').subscribe(result => {
      if (result)
        this.store.dispatch(new RequestRejectUsersAction(this.inactiveUsers));
    });
  }

  onApprove(user: User){
    let users: User[] = [user];
    this.store.dispatch(new RequestApproveUsersAction(users));
  }

  onReject(user: User){
    let users: User[] = [user];
    this.store.dispatch(new RequestRejectUsersAction(users));
  }
  
  onDelete(id: number){
    this.dialogService.confirm('Potvrzení', 'Opravdu si přejete smazat tento profil ?').subscribe(result => {
      if (result)
        this.store.dispatch(new RequestDeleteOtherUserAction(id));
    });
  }

  ngOnDestroy() {
    this.storeSubscription.unsubscribe();
  }
} 