// Angular Core
import { Component, Input, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
import { environment } from 'src/environments/environment';

@Component({
  standalone: false,
  selector: 'app-notification',
  templateUrl: './notification.component.html',
  styleUrls: ['./notification.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
export class NotificationComponent implements OnInit {

  @Input() item:any;
  @Input() supplier:any;
  @Input() fromCart:any;
  @Input() hazardous:any;
  @Input() refrigerated:any;
  @Input() imgStyle?: string = 'cart-notice-img';
  imgUrl: string = environment.imageUrl;

  constructor() { }

  bellImgId:string | undefined;
  notifImgId:string | undefined;

  ngOnInit(): void {
    this.generatePopUpContent();
                    
    this.iconImg = this.imgUrl+'/notification_bell.png';
    /**
    * notifImgId will set the id of Notif Img element.
    * If notifImgId is set with 'notifPopover' then Popovers will be displayed by default.
    * If notifImgId is not set then then Popovers will not be displayed by default.
    */
    this.notifImgId = undefined;
    this.bellImgId = undefined;
    if (this.fromCart) {
        this.notifImgId = 'notif_no_auto_display';
        this.bellImgId = 'notif_'+this.item.id;
    } else {
        if(this.item.is_refrigerated && this.refrigerated) {
            this.iconImg = this.imgUrl+'/refrigerated-new.png';
        } 
        if(this.item.is_hazardous && this.hazardous) {
            this.iconImg = this.imgUrl+'/hazardous.png';
        }
    }
  }

  /**
   * autoClose = false  //Will make the Popover close when user clicks on anywhere in Cart Page.
   * autoClose = true   //Will make the Popover remains open when user clicks on anywhere in Cart Page.
   */
  autoClose:boolean = false;
                
  iconImg:string = '';
  
  /**
   * Object containing the different mesgs objects
   */
  possibleMsgs:any = {
    refrigerated: {
        imgUrl: this.imgUrl+'/refrigerated.png',
        title: 'Requires Refrigeration',
        content: 'Overnight Shipping only, No Weekend Delivery.',
        subContent: 'Weekend days do not count towards shipping days.'
    },
    hazmat: {
        imgUrl: this.imgUrl+'/hazmat_icon.png',
        title: 'Hazardous Materials',
        content: 'This is a HAZMAT item and will force your entire order to ship Ground, You may want to order this item separately.',
        subContent: ''
    },
    refrigeratedParagon: {
        imgUrl: this.imgUrl+'/refrigerated.png',
        title: 'Requires Refrigeration',
        content: 'Overnight Shipping only, No Weekend Delivery.',
        subContent: 'Weekend days do not count towards shipping days.'
    },
    productShortage : {
        imgUrl: this.imgUrl+'/outOfStock.png',
        title: 'Product Shortage',
        content: 'The quantity on order for this product can no longer be met. Please review the quantity available and adjust your order.',
        subContent: ''
    },
    outOfStock: {
        imgUrl: this.imgUrl+'/outOfStock.png',
        title: 'Out of Stock ',
        content: 'This product is no longer available',
        subContent: ''
    },
    schedule2: {
        imgUrl: this.imgUrl+'/c2.png',
        title: 'CSOS Authentication Required',
        content: 'Placing an order for this item will require CSOS authentication and approval from the supplier. ',
        subContent: ''
    },
    groundShippingOnly: {
        imgUrl: this.imgUrl+'/groundonly_icon.png',
        title: ' Ground Shipping Only',
        content: 'This item may be shipped separately subject to Ground shipping only. ',
        subContent: ''
    },
    childFirstOrder: {
        imgUrl: '',
        title: 'Account Setup Notice',
        content: 'Please allow up to 24 business hours for Account Setup before order will \n\
                be Processed, this is your 1st order with this specific Distribution Center.',
        subContent: '',
        customClasses: ['acc-setup-notice']
    }
    //add more here when needed
  };

  /**
   * messages array to be displayed
   */
  messages:any[] = [];

  /**
   * add a message to the messages array
   * @returns {undefined}
   */
  addMsg(msg:any) {
      this.messages.push(msg);
  };

  /**
   * Display Hazardous Notification message by default when cart loads,
   * based on shipping methods conditions.
   * 
   * @param {object} item
   * @param {object} supplier
   * @returns {Boolean}
   */
  displayPopOverForHazardous(item:any, supplier:any) {
    if (item.is_hazardous) {
        var shippingMethods = supplier.shippingData.shipping_methods;
        if (this.groundShippingMet(shippingMethods) && !this.otherThanGroundShippingMthdsMet(shippingMethods)) {
            return false;
        }
        return true;
    }
    return false;
  };

  /**
   * Display Refrigerated Notification message by default when cart loads.
   * 
   * @param {object} item
   * @param {object} supplier
   * @returns {Boolean}
   */
  displayPopOverForRefrigerated(item:any, supplier:any) {
    if (item.is_refrigerated) {
        /**
         * As per TRX-6736, removed Weekend and Shipping method conditions
         * for Refrigerated product.
         * From now on, if a refrigerated product is added to cart then Notification
         * will be automatically displayed with out any condition.
         * 
         */
        return true;
    }
    return false;
  };

  /**
   * Display Ground Shipping Notification message by default when cart loads,
   * based on shipping methods conditions.
   * 
   * @param {object} item
   * @param {object} supplier
   * @returns {Boolean}
   */
  displayPopOverForGroundShippingOnly(item:any, supplier:any) {
    if (item.ground_shipping_only) {
        var shippingMethods = supplier.shippingData.shipping_methods;
        if (this.groundShippingMet(shippingMethods) && !this.otherThanGroundShippingMthdsMet(shippingMethods)) {
            return false;
        }
        return true;
    }
    return false;
  };

  /**
   * 
   * @param {type} shippingMethods
   * @returns {Boolean}
   */
  overNightShippingMet(shippingMethods:any) {
    var returnValue = false;
    shippingMethods.forEach((data:any) => {
      if(data.name === 'Overnight' && data.status === 'Minimum Met') {
        returnValue = true;
      }
    });
    return returnValue;
  };

  /**
   * 
   * @param {type} shippingMethods
   * @returns {Boolean}
   */
  groundShippingMet(shippingMethods:any) {
      var returnValue = false;
      shippingMethods.forEach((data:any) => {
        if(data.name === 'Ground' && data.status === 'Minimum Met') {
          returnValue = true;
        }
      });
      return returnValue;
  };

  /**
   * 
   * @param {type} shippingMethods
   * @returns {Boolean}
   */
  otherThanGroundShippingMthdsMet(shippingMethods:any) {
    var shippingMthds = ['2 Day', 'Overnight', 'Same Day'];
    var shippingStatus = ['Minimum Met'];
    var returnValue = false;
    shippingMethods.forEach((data:any) => {
      if(shippingMthds.indexOf(data.name) !== -1
                && shippingStatus.indexOf(data.status) !== -1) {
            returnValue = true;
      }
    });
    return returnValue;
  };

  /**
   * injects objects to be rendered in the messages array
   * @returns {undefined}
   */
  generatePopUpContent() {

    //check if item is controlled substance 2
    if(parseInt(this.item.dea_schedule) === 2) {
        this.addMsg(this.possibleMsgs.schedule2);
    }

    //check if hazmat
    if((this.item.is_hazardous && this.hazardous) || (this.item.is_hazardous && !this.hazardous && typeof(this.refrigerated) === 'undefined')) {
        this.addMsg(this.possibleMsgs.hazmat);
    } 
    
    //check if paragon refrigerated
    if(typeof(this.supplier) !== 'undefined' && this.item.is_refrigerated && this.supplier.shippingData["2day_refrg"]) {
        this.addMsg(this.possibleMsgs.refrigeratedParagon);
    //check if item is refrigerated
    } else if((this.item.is_refrigerated  && this.refrigerated) || (this.item.is_refrigerated  && !this.refrigerated && typeof(this.hazardous) === 'undefined')) {
        this.addMsg(this.possibleMsgs.refrigerated);
    }
    //check if order quantity is greater than the avaialble quantity
    if(this.item.quantity > this.item.avail_qty &&  this.item.avail_qty > 0) {
        this.addMsg(this.possibleMsgs.productShortage);
    }
    //check if out-of-stock
    if(this.item.sold_out || (this.item.item_available === false) || this.item.auction_expired) {
        this.addMsg(this.possibleMsgs.outOfStock);
    }
    //check if item is ground shipping only
    if(this.item.ground_shipping_only) {
        this.addMsg(this.possibleMsgs.groundShippingOnly);
    }
    
    if (this.item.is_child_first_order) {
        this.addMsg(this.possibleMsgs.childFirstOrder);
    }
  };

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