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

// RxJs
import { Subscription, catchError, throwError } from 'rxjs';

// Services
import { ReshopUnacceptedService } from 'src/app/services/reshopUnaccepted/reshop-unaccepted.service';
import { UtilitiesService } from 'src/app/services/utilities/utilities.service';
import { SessionService } from 'src/app/services/session/session.service';

// Interfaces
import { SessionDataInterface } from 'src/app/interfaces/session-data-interface';
import { environment } from 'src/environments/environment';
import { DataTransmitterService } from 'src/app/services/dataTransmitter/data-transmitter.service';

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

  session!: SessionDataInterface['data'];
  /**
   * 
   * avoid partial load if not logged in
   */
  renderMe!: boolean;
  qty:any = {};
  showItems:any = {};
  imgUrl: string = environment.imageUrl;
  
  /**
   * Fetch Reshop product details.
   * 
   * @returns {undefined}
   */
  searchUnaccepted!:Subscription;
  unaccepted!:any;
  shippingInfo!:any;
  unacceptedCount!:any;

  constructor(
    private sessionService : SessionService,
    private reshopUnaccepted: ReshopUnacceptedService,
    private utilitiesService: UtilitiesService,
    private dataTransmitter: DataTransmitterService
  ) { }

  ngOnInit(): void {
    let ndc = '';
    this.session = this.sessionService.getSession();
    this.renderMe = this.session.logged_in && (this.session.reg_step > 6) && this.session.is_buyer;
    this.searchUnaccepted = this.reshopUnaccepted.searchUnaccepted()
      .pipe(
        catchError(() => {
          return throwError(() => new Error('ups sommething happend'));
        })
      )
      .subscribe({
        next: (res: any) => {
          if (res.data.reshopAuctions !== undefined ) {
            this.unaccepted = res.data.reshopAuctions;
            this.shippingInfo = res.data.shippingInfo;
            ndc = this.unaccepted[0]['ndc'];
            this.unacceptedCount = Object.keys(this.unaccepted).length;
            this.initInputModels(this.unaccepted, false);
          }else {
              this.unacceptedCount = 0;
          }
          this.dataTransmitter.lane4AdData.next({ndc: ndc, pageName: 'ReshopUnaccepted'});
        },
        error: (err) => {
          this.reshopUnaccepted.errorCallBack(err);
        },
        complete: () => { },
      });
  }

  /**
   * Initialize all input models to the in cart qty
   * received from backend.
   * 
   * @param {object} reshop items
   * @returns {undefined}
   */
  initInputModels(unaccepted:any, update:boolean) {
    unaccepted.forEach((item:any) => {
      if (!update) {
          this.showItems[item.product_id] = 1;
      }
      this.qty[item.auction_id] = item.qty_in_cart;
    })
  };
  
  /**
   * Method to check if the Expiration Date is below 90 days or not
   * @param {string} expirationDate
   * @return {Boolean}
   */
  isExpireIn90Days(expirationDate: string) {
    return this.utilitiesService.getExpireDateBelow90Days(expirationDate);
  }
  
  /**
   * Unsubscirbe all the data when component is destroyed
   */
  ngOnDestroy(){
    this.searchUnaccepted?.unsubscribe();
  }

}
