import {Component, Inject, OnInit} from '@angular/core';
import {MD_DIALOG_DATA, MdDialogRef} from '@angular/material';
import {Select} from '../../share/_model/select';
import {User} from '../_model/user';
import {AdminService} from '../_service/admin.service';
import {BaseComponent} from '../../share/base.component';
import {Router} from '@angular/router';
import {MdSnackBar} from '@angular/material';

@Component({
  selector: 'app-dialog-user-info',
  templateUrl: '../_views/userInfo.dialog.html',
  styleUrls: ['../_views/userInfo.dialog.scss', '../../share/eclettica.scss']
})
export class UserInfoDialogComponent extends BaseComponent implements OnInit {
  user: User;
  roles: Array<Select>;
  loading: boolean;

  constructor(protected router: Router,
              protected mdSnackBar: MdSnackBar,
              private adminService: AdminService,
              public dialogRef: MdDialogRef<UserInfoDialogComponent>,
              @Inject(MD_DIALOG_DATA) public data: any) {
    super(router, mdSnackBar);
  }

  ngOnInit() {
    if (this.data) {
      this.user = this.data;
      console.log(this.user);
    } else {
      this.user = new User();
    }
    this.initRole();
  }

  initRole() {
    this.roles = [];
    this.roles[0] = new Select('ADMIN', 'Administrator');
    this.roles[1] = new Select('CON_PRO', 'Content provider');
    this.roles[2] = new Select('USER', 'Viewer user ');
  }

  save() {
    this.loading = true;
    if (this.user.userId) {
      this.adminService.updateUser(this.user).subscribe(res => {
        if (res.status === 'OK') {
          this.openSnackBar('Updated user successful!');
          this.dialogRef.close('OK');
        } else {
          this.processStatusError(res.errors);
        }
        this.loading = false;
      });
    } else {
      this.adminService.saveUser(this.user).subscribe(res => {
        if (res.status === 'OK') {
          this.openSnackBar('Created user successful!');
          this.dialogRef.close('OK');
        } else {
          this.processStatusError(res.errors);
        }
        this.loading = false;
      });
    }
  }
}
