import {Component, NgModule, OnInit} from '@angular/core';
import {AuthService} from '../services/auth.service';
import {NavigationEnd, Router} from '@angular/router';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {User} from '../models/user';


@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})

export class HomeComponent implements OnInit {

  public name = '';
  userInfo: User ;
  public data = [];
  showData = false;
  showMsg = false;
  userUpdateForm: FormGroup;
  isSubmitted: boolean;
  code:any;
  showModal: boolean = false;
  successMsg: any;
  taskTitle: any;
  deleteCheckModal: boolean = false;
  constructor(private authService: AuthService, private router: Router, private formBuilder: FormBuilder) { }

  ngOnInit() {
    this.userUpdateForm  =  this.formBuilder.group({
      userId: ['', Validators.required],
      email: ['', Validators.required],
      password: ['', Validators.required],
      name: ['', Validators.required],
      role: ['', Validators.required],
      description: ['', Validators.required]
    });
    if (!this.authService.isLoggedIn()) {
      this.router.navigate(['/index/login']);
    } else {
      this.name = localStorage.getItem('token');
      this.authService.AllUsers().subscribe(
        response => {
          this.data = response;
        });
    }
  }
  get formControls() { return this.userUpdateForm.controls; }
  getData(data) {
    this.showData = true;
    this.userInfo = data;
  }
  taskId:any
  dat:any = {};
  deleteData(id): void {
    console.log(id);
    this.taskId = id;
    this.authService.deleteData(this.taskId).subscribe(dat => {

        this.showModal = true;
        window.location.reload();
    },
    error => {
      console.log("error", error);
     
    });
  }
  logout() {
    this.authService.logout();
    this.router.navigateByUrl('/index/login');
  }
  update() {
    console.log(this.userUpdateForm.value);
    this.isSubmitted = true;
    if (this.userUpdateForm.invalid) {
      return;
    }
    this.authService.update(this.userUpdateForm.value).subscribe(
      response => {

        if (response !== undefined && response !== null) {
          console.log('Successfully updated Data...');
          window.location.reload();
          this.showMsg = true;
        } else {
          console.log('Invalid Data...');
        }
      },
      error => {
        console.log('Error in authentication');
      });
  }
}