import { Component, HostListener, Input, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { PageEvent } from '@angular/material/paginator';
import { Sort } from '@angular/material/sort';
import { AuthService } from 'src/app/services/auth.service';
import { UserManagementService } from 'src/app/services/user.management.service';
import { ConfirmDialog } from 'src/app/ui/confirm/confirm.component';

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

  @Input() users: any;
  pageSizeOptions: number[] = [1, 2, 3, 4, 5, 10, 15, 30, 50, 100];
  sort: string = "username";
  descending: boolean = false;

  columns: string[] = [];

  form: FormGroup;
  isAdmin: boolean = false;

  username: string = "";

  constructor(
    private userManagementService: UserManagementService,
    private authService: AuthService,
    private formBuilder: FormBuilder) { }

  ngOnInit(): void {
    this.users = {};
    this.update();
    this.applyResize(window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth);
    this.form = this.formBuilder.group({
      username: ['', Validators.required],
      name: ['', Validators.nullValidator],
      email: ['', Validators.nullValidator],
      password: ['', Validators.required]
    });

    this.authService.auth.subscribe({
      next: (auth) => {
        this.username = auth.username;
      },
      error: (error) => {
        this.username = ""
      }
    })
  }

  @HostListener('window:resize', ['$event'])
  onResize(event) {
    this.applyResize(event.target.innerWidth || event.target.documentElement.clientWidth || event.target.body.clientWidth)
  }

  applyResize(width: number) {
    if (width < 992) {
      this.columns = ['username', 'name', 'email']
    } else {
      this.columns = ['username', 'name', 'email', 'about'];
    }
  }

  update() {
    this.userManagementService.fetch(this.users.limit || 15, this.users.offset || 0, this.sort, this.descending).subscribe({
      next: (data: any) => {
        this.users = data;
      }, error: (error) => {
        this.users = { error: error };
      }
    })
  }

  applyPage(event: PageEvent) {
    this.users.limit = event.pageSize;
    this.users.offset = event.pageSize * event.pageIndex;
    this.update();
  }

  applySort(event: Sort) {
    this.sort = event.direction ? event.active : 'username';
    this.descending = event.direction !== 'asc';
    this.update();
  }

  createUser() {
    const user = {
      username: this.form.get("username").value,
      name: this.form.get("name").value,
      email: this.form.get("email").value,
      roles: this.isAdmin ? ['ROLE_ADMIN'] : []
    }
    this.userManagementService.create(user).subscribe({
      next: (result: any) => {
        this.userManagementService.setPassword(result.username, this.form.get("password").value).subscribe({
          next: (result) => {
            this.update();
          },
          error: (error) => {
            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.form.get(code).setErrors(errors[code]);
              }
            }
          }
        });
      },
      error: (error) => {
        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.form.get(code).setErrors(errors[code]);
          }
        }
      }
    })
  }

}
