// Angular Core
import { Pipe, PipeTransform } from '@angular/core';

// Services
import { CartService } from '../services/cart/cart.service';

// Third Party
import * as jstz from 'jstz';

@Pipe({
  name: 'timezone',
  standalone: false
})
export class TimezonePipe implements PipeTransform {

  constructor(
    private cartService: CartService
  ){ }
  transform(value: unknown, ...args: unknown[]): unknown {
    var timezoneAbbr:{ [key: string]: string } = {
      "America/Chicago": "CT",
      "America/Los_Angeles": "PT",
      "America/New_York": "ET",
      "America/Indiana/Indianapolis": "ET",
      "America/Kentucky/Louisville": "ET",
      "America/Denver": "MT",
      "America/Detroit": "ET",
      "America/Phoenix": "MT",
      "America/North_Dakota/New_Salem": "CT",
      "Pacific/Honolulu": "HST",
      "America/Puerto_Rico": "AST",
      "America/Kentucky/Monticello": "ET",
      "America/Boise": "MT"
  };
    let timezoneId = '';
    let timezoneval = '';
    var tz = jstz.determine(); // Determines the time zone of the browser client
    var zoneName = tz.name(); // like 'America/New_York'
    timezoneId = timezoneAbbr[zoneName];
    
    if(timezoneId) {
      var estOffset = this.cartService.getEstOffset();
      var now:Date = new Date();

      //Get supplier cutoff time in milliseconds
      var time:any = this.cartService.getSupplierCutOffTimeObj(estOffset, value);

      //Get current time in supplier timezone
      var d:Date = new Date();
      var d_sethours:any = d.setHours(now.getHours(), now.getMinutes(), now.getSeconds(), now.getMilliseconds())
      var d_sethours_in_int = parseInt(d_sethours)
      var d_get_timezone_offset:any = d.getTimezoneOffset() * 60 * 1000
      var utc = d_sethours_in_int + parseInt(d_get_timezone_offset);
      var currSuppTime = utc - estOffset;

      //Difference between current time and supplier time
      var diff:any = time - currSuppTime;
      diff = parseInt(diff)

      //Get current time in usertime zone
      var currTime = new Date();
      var hours = 0;
      var minutes:any = 0;
      var period = 'AM';
      time = new Date(new Date().setHours(currTime.getHours(), currTime.getMinutes(), currTime.getSeconds(), currTime.getMilliseconds()) + diff);
      hours = time.getHours();
      minutes = time.getMinutes();

      if (hours >= 12) {
        period = 'PM';
        if (hours > 12) {
            hours = hours - 12;
        }
      }
      minutes = minutes.toString().length === 1 ? '0' + minutes : minutes;

      timezoneval = hours + ':' + minutes + ' ' + period + ' ' + timezoneId;
    }else{
      timezoneval = value + ' ET';
    }
    return timezoneval;
  }

}
