// Angular Core
import { Component, Input, OnInit, ChangeDetectionStrategy, ComponentFactoryResolver, Injector } from '@angular/core';
import { KeyValue } from '@angular/common';
import { TrxademodalService } from 'src/app/services/trxademodal/trxademodal.service';
import { DateRangeSelectPopUpComponent } from '../date-range-select-pop-up/date-range-select-pop-up.component';
import { DataTransmitterService } from 'src/app/services/dataTransmitter/data-transmitter.service';

@Component({
  standalone: false,
    changeDetection: ChangeDetectionStrategy.OnPush,
    selector: 'app-shipping-settings-body',
    templateUrl: './shipping-settings-body.component.html',
    styleUrls: ['./shipping-settings-body.component.scss'],
})
export class ShippingSettingsBodyComponent implements OnInit {

    @Input() shippingType!: string;
    @Input() shippingInfo!: any;
    @Input() isProdTypeEnabled!: number | boolean;
    @Input() cutOffClosedDays!: any;
    shippingCutOffs: {[key: string]: string} = {
        mon: '00:00',
        tue: '00:00',
        wed: '00:00',
        thu: '00:00',
        fri: '00:00'
    }

    cutOffDays = {
        mon: 'Monday',
        tue: 'Tuesday',
        wed: 'Wednesday',
        thu: 'Thursday',
        fri: 'Friday'
    };

    shippingSettings = {
        hideGround: false,
        hideSameDay: false,
        hideDropShipping: false,
        prodTypeEnabled: this.isProdTypeEnabled,
        varName: 'd',
        brandPrefix: 'd_b',
        genericPrefix: 'd_g'
    };

    constructor(private trxadeModalService: TrxademodalService, private componentFactory: ComponentFactoryResolver, private injector: Injector, private dataTrasmitter: DataTransmitterService) { }

    ngOnInit(): void {
        let cutOffClosedDays: string[] = [];
        this.cutOffClosedDays.forEach((value: any, key: any) => {
            if (new Date(value.fromDate) < new Date()) {
                (this.shippingCutOffs as any)[value.day] = 'closed';
                cutOffClosedDays.push(value.day);
            }
        });
        Object.keys(this.shippingCutOffs).forEach((day: string) => {
            if (cutOffClosedDays.indexOf(day) === -1) {
                (this.shippingCutOffs as any)[day] = this.shippingInfo['order_cutoff_'+ day]
            }
        });
        this.dataTrasmitter.cutOffClosedDateRange.subscribe((data: any) => {
            let foundDay = false
            this.cutOffClosedDays.forEach((value: any, key: number) => {
                if (data.day === value.day) {
                    this.cutOffClosedDays[key] = data;
                    foundDay = true;
                }
            });
            if (!foundDay) {
                this.cutOffClosedDays.push(data);
            }
        });

        if (this.shippingType !== undefined && this.shippingType === 'pr') {
            this.shippingSettings.hideGround = true;
            this.shippingSettings.hideSameDay = true;
            this.shippingSettings.varName = 'p';
            if (this.isProdTypeEnabled === 1) {
                this.shippingSettings.brandPrefix = 'p_d';
                this.shippingSettings.genericPrefix = 'p_g';
            }
        }
        if (this.shippingType !== undefined && this.shippingType === 'hw') {
            this.shippingSettings.hideSameDay = true;
            this.shippingSettings.varName = 'h';
            if (this.isProdTypeEnabled === 1) {
                this.shippingSettings.brandPrefix = 'h_d';
                this.shippingSettings.genericPrefix = 'h_g';
            }
        }

        /**
         * TRX-7741: added GU state shipping type condition
         */
        if (this.shippingType !== undefined && this.shippingType === 'gu') {
            this.shippingSettings.hideGround = true;
            this.shippingSettings.hideSameDay = true;
            this.shippingSettings.varName = 'g';
            if (this.isProdTypeEnabled === 1) {
                this.shippingSettings.brandPrefix = 'g_d';
                this.shippingSettings.genericPrefix = 'g_g';
            }
        }
    }

    filterFloatValue(elementEvent: any) {
        parseFloat(elementEvent.target.value);
    };

    /**
     * As per TRX-7683,
     * Filter input value to accept only integer.
     * @param elementEvent
    */
    filterIntegerValue(elementEvent: any) {
        parseInt(elementEvent.target.value);
    };

    // Trackby function for track looping items
    trackByFn(index: number, item: any) {
        if (item.key) {
            return item.key;
        }
        return index;
    }

    // Preserve original property order
    originalOrder = (a: KeyValue<string, string>, b: KeyValue<string, string>): number => {
        return 0;
    }

    getfilterFloatValueData(event: any) {
        this.filterFloatValue(event);
    }

    /**
     * Open pop up to select date range required to mark cutoff days as closed
     * @param event 
     * @param day 
     * @param dayKey 
     */
    openDateRangePopUp(event: any, day: string, dayKey: string) {
        if (event.target.value === 'closed') {
            this.trxadeModalService.modalPipe.next({
                component: this.componentFactory.resolveComponentFactory(DateRangeSelectPopUpComponent).create(this.injector).instance,
                data: { day: day, dayKey: dayKey },
                showModal: true
            });
        } else {
            this.shippingInfo['order_cutoff_'+ dayKey] = event.target.value;
            const dayExists = this.cutOffClosedDays?.some((closedDay: any) => closedDay.day === dayKey) ?? false;
            if (dayExists) {
                // Transmits the Data with Default Date values if CutOff is changed from Closed to time
                this.dataTrasmitter.cutOffClosedDateRange.next({
                  day: dayKey,
                  fromDate: '0000-00-00',
                  toDate: '0000-00-00'
              });
            }
        }
    }
}
