// Angular Core
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';

// RxJs
import { throwError } from 'rxjs';
import { catchError } from "rxjs/operators";

// Services
import { MainSettingsService } from 'src/app/services/mainSettings/main-settings.service';

// Interfaces
import { activeADRInterface, saveMainSettingsInterface } from 'src/app/interfaces/common-interfaces';

@Component({
  standalone: false,
  selector: 'app-active-adr',
  templateUrl: './active-adr.component.html',
  styleUrls: ['./active-adr.component.scss']
})
export class ActiveAdrComponent implements OnInit {

  @Input() activeAdr!:activeADRInterface['data'];
  @Input() labeler_code!:any;
  @Output() isFailed = new EventEmitter<boolean>();
  @Output() isSuccessed = new EventEmitter<boolean>();

  constructor(private mainSettings: MainSettingsService) { }

  ngOnInit(): void {
  }
   
  /**
   * Remove ADR Code
   * @param string labelerCode
  */
    removeADR (labelerCode:string){
    this.mainSettings
    .removeADR(labelerCode)
    .pipe(
      catchError(() => {
        return throwError(() => new Error('ups sommething happend'));
      })
    )
    .subscribe({
      next: () => {
          this.mainSettings.getActiveADR()
          .pipe(
            catchError(() => {
              return throwError(() => new Error('ups sommething happend'));
            })
          ).subscribe({
            next: (res: activeADRInterface) => {
              this.activeAdr = res.data;
            },
            error: (err) => {
              this.mainSettings.errorCallBack(err);
            },
            complete:() => {}
          });
      },
      error: (err) => {
        this.mainSettings.errorCallBack(err);
      },
      complete:() => {}
    });
  };

  /**
    * Validate ADR Code
    * @param string labelerCode
  */
  validateADRCode(){
      this.closeMsg();
        if (typeof this.labeler_code === 'object') {
            this.labeler_code = this.labeler_code.labeler_code;
        }
      var DataSet = {"labelerCode":this.labeler_code}
      this.mainSettings
      .saveMainSettings(DataSet)
      .pipe(
        catchError(() => {
          return throwError(() => new Error('ups sommething happend'));
        })
      )
      .subscribe({
        next: (res: saveMainSettingsInterface) => {
          let response = JSON.stringify(res);
            this.isSuccessed.emit(true);
            this.mainSettings.getActiveADR()
            .pipe(
              catchError(() => {
                return throwError(() => new Error('ups sommething happend'));
              })
            ).subscribe({
              next: (res: activeADRInterface) => {
                this.activeAdr = res.data;
              },
              error: (err) => {
                this.mainSettings.errorCallBack(err);
              },
              complete:() => {}
            });
        },
        error: (err) => {
          this.isFailed.emit(true);
          this.mainSettings.errorCallBack(err);
        },
        complete:() => {}
      });

  };

  /**
  * Close success/fail ADR validation message
  * 
  */
  closeMsg(){
      this.isSuccessed.emit(false);
      this.isFailed.emit(false);
  };

  // Trackby function for track looping items
  trackByFn(index:number, item: activeADRInterface['data'][0]){
    return item
  }

}
