import { Component, Input, OnInit } from '@angular/core';
import { NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import { Subscription } from 'rxjs';

import { CartService } from 'src/app/services/cart/cart.service';
import { Router } from '@angular/router';

@Component({
  standalone: false,
  selector: 'app-re-order-items-modal',
  templateUrl: './re-order-items-modal.component.html',
  styleUrls: ['./re-order-items-modal.component.scss']
})
export class ReOrderItemsModalComponent implements OnInit {

    @Input() reOrderModalClose!: () => void;
    @Input() orderItems!: any;
    @Input() ReOrderItemsModal!:NgbModalRef;
    orderData:any = {};

    constructor( private cartService: CartService, private router: Router) { }

    ngOnInit(): void {
    }

    /*
    * method to Order same products again
    * @return void
    */
    reOrderItemsSubscribe!: Subscription;
    reOrderItems(orderItems: any) {
        orderItems.forEach((orderItem: any) => {
            this.orderData[orderItem.auction_id] = {
                'quantity' : orderItem.quantity_requested,
                'supplierId': orderItem.seller_id,
                'item_price' : orderItem.bid_amount,
                'from_page'  : 'ManagePurchases'
            };
        });
        this.reOrderItemsSubscribe = this.cartService.reOrderItems(this.orderData)
        .subscribe({
          next: () => {
            this.reOrderModalClose();
            this.cartService.RefreshQuickCart.emit('');
            //trigger event to refresh quickcart
            this.cartService.QuickCart.emit("");
            //Refresh shipping options
            this.cartService.updateShippingInfo.emit({});
            this.router.navigate(['/market/cart'])
          },
          error: (err) => {
            this.cartService.errorCallBack(err);
          },
          complete: () => { },
        })
    };
}
