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

// Services
import { CartService } from 'src/app/services/cart/cart.service';
import { environment } from 'src/environments/environment';

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

  @Input() cutoffTime!: string;
  @Input() supplierId!: number;
  @Input() cutoffType!: string;
  @Input() supplier!: any;
  imgUrl: string = environment.imageUrl;

  constructor(
    private cartService: CartService,
  ) { }

  cutOffTimer = '';
  totalSeconds = 0;
  cutoffTimeObj: any = {}
  cutoffTimerText = '';
  cutoffTimerExpireText = '';
  currentTime: any;

  ngOnInit(): void {
    this.cutoffTimeObj['cutoffTimeExpired_'+this.supplierId] = false;
    this.cutoffTimeObj['estAfterCutOffFlag_'+this.supplierId] = false;
    setInterval(() => {
      if (this.cutoffTime !== undefined && this.cutoffTime !== null && this.cutoffTime !== '') {
            this.setCurrentTime();
            var suppCutOffStartTime = this.cartService.getSupplierCutOffTimeObj(this.cartService.getEstOffset(), this.cutoffTime);
            var suppCutOffEndTime = this.cartService.getSupplierCutOffTimeObj(this.cartService.getEstOffset(), this.cutoffTime);
            var timeParts = this.cutoffTime.match(/(\d+):(\d+) (AM|PM)/);
            var hours = 0;
            var minutes = 0;

            if (timeParts) {
                hours = parseInt(timeParts[1]);
                minutes = parseInt(timeParts[2]);
                if (timeParts[3] === 'PM' && hours < 12) {
                    hours += 12;
                }
                suppCutOffStartTime.setHours(hours - 1);
                suppCutOffStartTime.setMinutes(minutes);
                suppCutOffEndTime.setHours(hours);
                suppCutOffEndTime.setMinutes(minutes);
            }
            if (this.currentTime.getTime() >= suppCutOffStartTime.getTime() 
                    && this.currentTime.getTime() <= suppCutOffEndTime.getTime()
                    && this.cutOffTimer !== '0:00:00') {
                this.totalSeconds = Math.floor((suppCutOffEndTime.getTime() - this.currentTime.getTime())/1000);
                var hours   = Math.floor(this.totalSeconds / 3600 );
                var minutes = Math.floor(this.totalSeconds % 3600 / 60);
                var seconds = this.totalSeconds % 60;
                if (minutes < 10) {
                    minutes = Number('0'+minutes);
                }
                if (seconds < 10) {
                    seconds = Number('0'+seconds);
                }
                this.cutOffTimer = [hours, minutes, seconds].join(':');
                this.cutoffTimerText = 'Time remaining for your order to be acknowledged same day';
            }
            
            if (this.cutOffTimer === '0:00:00' || this.currentTime.getTime() > suppCutOffEndTime.getTime() || this.cutoffTime === 'Closed Today') {
                if (this.supplier.supplierData.is_prime_supplier && this.cutoffTimeObj['estAfterCutOffFlag_'+this.supplierId] === false) {
                    this.cutoffTimeObj['estAfterCutOffFlag_'+this.supplierId] = true;
                    if (this.supplier.shippingData.selectedShipping === undefined || this.supplier.shippingData.selectedShipping === null
                        || this.supplier.shippingData.selectedShipping === '') {
                        this.supplier.shippingData.selectedShipping = "Ground";
                    }
                    this.cartService.getETADLVRItems(this.supplier, this.supplier.shippingData.selectedShipping);
                }
                this.cutOffTimer = '';
                this.cutoffTimeObj['cutoffTimeExpired_'+this.supplierId] = true;
                this.cutoffTimerExpireText = 'The cutoff time for this supplier has passed. Any orders placed after this time may not get processed until the following business day.';
            }             
        }
    }, 1000);
  }

  /**
   * Sets Current Time in User timezone in $scope.currentTime.
   * @returns {undefined}
   */
  setCurrentTime(){
    let now = new Date();
    let currentDay = new Date();
    let time = currentDay.setHours(now.getHours(), now.getMinutes(), now.getSeconds(), now.getMilliseconds()) + (currentDay.getTimezoneOffset() * 60 * 1000) - this.cartService.getEstOffset();
    this.currentTime = new Date(time);
  };

}