import { Component, OnDestroy, OnInit } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { concatMap, flatMap, map, switchMap, take, tap } from "rxjs/operators";
import { ClientService } from "../clients.service";
import { GlobalService } from '../global.service';

@Component({
  selector: "app-clients-edit",
  templateUrl: "./clients-edit.component.html",
  styleUrls: ["./clients-edit.component.scss"],
})
export class ClientsEditComponent implements OnInit, OnDestroy {
  public client: any;
  public interest: any;
  public selectedBrand: any;

  public alerts = [];
  private sub: any;
  globals: GlobalService;

  constructor(
    private readonly route: ActivatedRoute,
    private readonly clientService: ClientService,
    private readonly globalsService: GlobalService,
    private router: Router
  ) {
    this.client = {};
    this.interest = {};
    this.globals = globalsService;
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }

  ngOnInit(): void {
    this.sub = this.route.params
      .pipe(flatMap((params) => this.clientService.getClientById(params.id)))
      .subscribe(
        (client) => {
          this.client = client[0] || {};
          this.interest = this.client.interests || {};
          delete this.interest.id;
        },
        (error) => {
          console.error(error);
        }
      );
  }

  public onFormSubmit() {
    this.alerts = [];

    const flag = this.client && this.client.id;
    const addUpdate$ =
      flag
        ? this.clientService.updateClient(this.client)
        : this.clientService.addClient(this.client);

    addUpdate$
      .pipe(
        take(1),
        switchMap((client: any) => {
          this.client = client[0] || client || {};
          return this.clientService.addInterest(this.client.id, this.interest);
        })
      )
      .subscribe(
        (client: any) => {
          if (!flag) {
            return this.router.navigateByUrl('/clients/' + client.id);
          }
          this.client = client;
          this.interest = client.interests;
          delete this.interest.id;
          delete this.interest.createdAt;
          delete this.interest.updatedAt;
          this.alerts.push({ type: "success", message: "The client was successfully updated." });
        },
        (error) => {
          console.error(error);
          if(error.status == 404) {
            this.alerts.push({
              type: "warning",
              message: "The data were saved but we could not find a matching robot for this client.",
            });
          } else {
            this.alerts.push({
              type: "danger",
              message: "There was an error while updating the client.",
            });
          }
        }
      );
  }
}
