import { Component, OnInit }    from '@angular/core';
import { Router, ActivatedRoute }               from '@angular/router';
import { ConsumerService }      from '../services/consumer-service';
import { ConsumerData }     from '../models/consumer-data';
import 'rxjs/operator';


@Component({
  selector: 'cons-userlist',
  templateUrl: '../templates/user-list.template.html'
})
export class UserListComponent implements OnInit {

  tabContext: String = 'Users';

  searchFor: String = '';

  userlist: ConsumerData[] = [];

  selectedUser: ConsumerData = new ConsumerData();

  constructor(
      private route: ActivatedRoute,
      private router: Router,
      private consumerService: ConsumerService) {
  }

  ngOnInit(): void {
 // this.getUserList();
  }

  onFindUser(): void {
    this.findUsers(this.searchFor);
  }

  onFindUserKeyUp(event: any) {
    if (event.keyCode === 13) {
      this.onFindUser();
    }
  }

  findUsers(str: any): void {
    this.selectedUser = new ConsumerData();
    this.consumerService.findUsers(str)
        .subscribe(
            (data: ConsumerData[]) => {
              this.userListResponse(data);
            }
        );
  }

  getUserList(): void {
    this.selectedUser = new ConsumerData();
    this.consumerService.getUserList()
        .subscribe(
            (data: ConsumerData[]) => {
              this.userListResponse(data);
            }
        );
  }

  selectUser(user: ConsumerData): void {
    this.selectedUser = user;

  }

  private userListResponse(users: ConsumerData[]): void {
    this.userlist = users;
  }

  onSaveUser(): void {
    this.consumerService.saveUser(this.selectedUser)
        .subscribe(
            (data: ConsumerData) => {
              this.saveUserResponse(data);
            }
        );
  }

  private saveUserResponse(user: ConsumerData): void {
    if (user !== null) {
      this.onCancelChange();
    } else 

  }

  onCancelChange(): void {
    this.onFindUser();
  }


}

{
 // show error
    }