import { ValidateProfilePasswords } from './../../shared/custom.validators';
import { MatDialog } from '@angular/material/dialog';
import { RequestDeleteUserAction, RequestDeleteOtherUserAction, RequestUpdateOtherUserAction, RequestUpdateUserAction } from './../store/auth.actions';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { AbstractFormComponent } from './../abstract-form.component';
import { ActivatedRoute, ActivatedRouteSnapshot, Router } from '@angular/router';
import { AuthState } from 'src/app/auth/store/auth.reducers';
import { Subscription } from 'rxjs';
import { Store } from '@ngrx/store';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { AppState } from 'src/app/store/app.reducers';
import { User } from '../../core/model/user.model';
import { RequestUserAction, RequestUsersAction } from '../store/auth.actions';
import { ConfirmDialogComponent, ConfirmDialogData } from 'src/app/core/confirm-dialog/confirm-dialog.component';

@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.scss']
})
export class ProfileComponent extends AbstractFormComponent implements OnInit, OnDestroy {
  private profileForm: FormGroup = this.userToProfileForm();
  private editUserMode: boolean = false;
  public loggedUserId: number = null;

  private storeSubscription: Subscription;

  constructor( private route: ActivatedRoute, private store: Store<AppState>, private router: Router, private dialog: MatDialog) {
    super();
  }

  ngOnInit() {
    let routeSnapshot: ActivatedRouteSnapshot = this.route.snapshot;
    let id: String = routeSnapshot.paramMap.get('id');    

    this.storeSubscription = this.store.select('authState').subscribe(
      (state: AuthState) => {
        if (id !== null){
          this.editUserMode = true;
          if (state.users !== null){
            let users: User[] = state.users.filter(
              (user: User) => { return user.id === +id ? user : null; }
            );
            if (users.length < 1)
              this.router.navigate(['/profiles']);
            else {
              let user: User = users.pop();
              if ((state.user !== null && user.id === state.user.id) || !user.active)
                this.router.navigate(['/profiles']);
              this.loggedUserId = state.user ? state.user.id : null;
              this.profileForm = this.userToProfileForm(user);
            }
          }
          else{
            this.store.dispatch(new RequestUsersAction());
          }
        }
        else{
          if (state.user !== null){
            this.loggedUserId = state.user ? state.user.id : null;
            this.profileForm = this.userToProfileForm(state.user);
          }
          else
            this.store.dispatch(new RequestUserAction()); 
        }
      }
    );
  }

  private userToProfileForm(user?: User): FormGroup{
    let formControls = {
      'firstName': new FormControl(user ? user.firstName : null, Validators.required),
      'lastName': new FormControl(user ? user.lastName: null, Validators.required),
      'email': new FormControl(user ? user.email : null, [Validators.required, Validators.email]),
      'company': new FormControl(user ? user.company : null),
      'position': new FormControl(user ? user.position : null),
      'newPassword': new FormControl(null),
      'confirmNewPassword': new FormControl(null)
    };

    if (this.editUserMode){
      formControls['id'] = new FormControl(user ? user.id : null);
      formControls['role'] = new FormControl(user ? user.role.name : null);
    }
    else
      formControls['oldPassword'] = new FormControl(null)

    return new FormGroup(formControls, {
      validators: ValidateProfilePasswords
    });
  }

  onProfileSubmit(){
    if (this.editUserMode){
      this.store.dispatch(new RequestUpdateOtherUserAction(this.profileForm));
    }
    else{
      this.store.dispatch(new RequestUpdateUserAction(this.profileForm));
    }
  }

  onDeleteProfile(){
    let dialogData: ConfirmDialogData = {
      title: 'Potvrzení',
      text: 'Opravdu chcete tento profil smazat ?'
    }

    const dialogRef = this.dialog.open(ConfirmDialogComponent, {
      maxWidth: '300px',
      data: dialogData
    });

    dialogRef.afterClosed().subscribe(result => {
      if (result){
        if (this.editUserMode)
          this.store.dispatch(new RequestDeleteOtherUserAction(this.profileForm.controls['id'].value));
        else
          this.store.dispatch(new RequestDeleteUserAction());
      }
    });
  }

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

}
