import { Component, OnDestroy, OnInit } from '@angular/core';
import { AbstractControlOptions, FormBuilder, FormGroup, Validators } from '@angular/forms';

import { UserService } from '../../services/user.service';
import { ActivatedRoute, Router } from '@angular/router';
import { UserManagementService } from 'src/app/services/user.management.service';
import { MatchingValidator } from 'src/app/utils/matching.validator';
import { ConfirmDialog } from 'src/app/ui/confirm/confirm.component';
import { MatDialog } from '@angular/material/dialog';

@Component({
  selector: 'page-profile',
  templateUrl: './profile.page.html',
  styleUrls: ['./profile.page.scss']
})
export class PageProfile implements OnInit, OnDestroy {

  auth: any;
  user: any;
  working: boolean = false;
  profileSuccess: boolean = false;
  profileForm: FormGroup;
  passwordSuccess: boolean = false;
  passwordForm: FormGroup;
  admin: boolean = false;
  isAdmin: boolean = false;

  constructor(
    private userService: UserService,
    private userManagementService: UserManagementService,
    private formBuilder: FormBuilder,
    private router: Router,
    private route: ActivatedRoute,
    public dialog: MatDialog) { }

  ngOnInit(): void {
    this.profileForm = this.formBuilder.group({
      username: [{ disabled: true }, Validators.nullValidator],
      email: ['', Validators.nullValidator],
      name: ['', Validators.nullValidator],
      about: ['', Validators.nullValidator]
    });

    this.passwordForm = this.formBuilder.group({
      password: ['', Validators.nullValidator],
      password2: ['', Validators.nullValidator]
    }, {
      validator: MatchingValidator('password', 'password2')
    } as AbstractControlOptions);

    this.profileForm.get('username').disable();

    let userFetch = this.userService.get();
    if (this.route.snapshot.paramMap.has('username')) {
      this.admin = true;
      userFetch = this.userManagementService.get(this.route.snapshot.paramMap.get('username'));
    }

    userFetch.subscribe({
      next: (user) => {
        this.user = user;
        this.isAdmin = this.user.roles && this.user.roles.indexOf('ROLE_ADMIN') != -1;
        this.profileForm.get('username').setValue(this.user.username);
        this.profileForm.get('name').setValue(this.user.name);
        this.profileForm.get('email').setValue(this.user.email);
        this.profileForm.get('about').setValue(this.user.about);
      }
    })

  }

  ngOnDestroy(): void {
  }

  profileHasError(controlName: string): boolean {
    return this.profileForm.controls[controlName].errors != null;
  }

  saveProfile(): void {
    if (this.working) {
      return;
    }

    this.working = true;
    this.profileSuccess = false;

    this.user.about = this.profileForm.get('about').value;
    this.user.email = this.profileForm.get('email').value;
    this.user.name = this.profileForm.get('name').value;

    if (this.isAdmin && (!this.user.roles || this.user.roles.indexOf('ROLE_ADMIN') == -1)) {
      this.user.roles = this.user.roles || [];
      this.user.roles.push('ROLE_ADMIN');
    } else if (!this.isAdmin && this.user.roles && this.user.roles.indexOf('ROLE_ADMIN') != -1) {
      this.user.roles.splice(this.user.roles.indexOf('ROLE_ADMIN'), 1);
    }

    const create = this.admin ? this.userManagementService.update(this.user) : this.userService.update(this.user);

    create.subscribe({
      next: (data) => {
        this.user = data;
        this.isAdmin = this.user.roles && this.user.roles.indexOf('ROLE_ADMIN') != -1;
        this.working = false;
        this.profileSuccess = true;
      },
      error: (error) => {
        this.working = false;
        if (error.status == 422) {
          let errors = {};
          for (let code of error.error) {
            errors[code.field] = errors[code.field] || {};
            errors[code.field][code.code] = true;
          }

          for (let code in errors) {
            this.profileForm.get(code).setErrors(errors[code]);
          }
        }
      }
    })

  }

  setPassword() {
    if (this.working) {
      return;
    }

    this.working = true;
    this.passwordSuccess = false;
    this.userManagementService.setPassword(this.user.username, this.passwordForm.get('password').value).subscribe({
      next: () => {
        this.working = false;
        this.passwordSuccess = true;
      },
      error: (error) => {
        this.working = false;
        if (error.status == 409) {
          let errors = {};
          for (let code of error.error) {
            errors[code.field] = errors[code.field] || {};
            errors[code.field][code.code] = true;
          }

          for (let code in errors) {
            this.passwordForm.get(code).setErrors(errors[code]);
          }
        }
      }
    })
  }



  deleteUser() {
    const dialogRef = this.dialog.open(ConfirmDialog, {
      data: {
        'label': 'user.confirmDelete',
        'args': [this.user.username]
      }
    })

    dialogRef.afterClosed().subscribe({
      next: (result) => {
        if (result) {
          this.userManagementService.deleteUser(this.user.username).subscribe({
            next: () => {
              this.router.navigateByUrl('/');
            }
          });
        }
      }
    });
  }
}
