import { Component, OnInit } from '@angular/core';
import {ApiService} from '../services/api.service';
import {UserModel} from '../models/user.model';
import {Router} from '@angular/router';
import {LoginService} from '../services/login.service';


@Component({
  selector: 'app-settings',
  templateUrl: './settings.component.html',
  styleUrls: ['./settings.component.scss']
})
export class SettingsComponent implements OnInit {

  user: UserModel = new UserModel();  // user to edit
  password = '';                      // new password
  messageUser = '';                   // messages for user and pass part
  messagePass = '';

  constructor(
    private api: ApiService,
    private login: LoginService,
    private router: Router
  ) { }

  ngOnInit(): void {
    this.api.get<UserModel>('/user', data => {
      this.user.deserialize(data);
    });
  }

  saveUser() {
    this.api.put<UserModel>('/user', this.user.sendFormat(), (data, err) => {
      if (err) {
        this.messageUser = err.error.status;
      }
      else {  // login with new credentials
        this.login.login(data.name).then(res => {
          if (res) {
            this.router.navigate(['/samples']);
          }
          else {
            this.messageUser = 'request not successful, try again';
          }
        });
      }
    });
  }

  savePass() {
    this.api.put<UserModel>('/user', {pass: this.password}, (ignore, err) => {
      if (err) {
        this.messagePass = err.error.status;
      }
      else {  // login with new credentials
        this.login.login('', this.password).then(res => {
          if (res) {
            this.router.navigate(['/samples']);
          }
          else {
            this.messagePass = 'request not successful, try again';
          }
        });
      }
    });
  }

}
