import { Pipe, PipeTransform } from '@angular/core'
import { HelperService } from '../services/helper.service'

@Pipe({
  name: 'sasToJsDate',
  standalone: false
})
export class sasToJsDatePipe implements PipeTransform {
  constructor(private helperService: HelperService) {}

  transform(
    sasValue: string | number,
    sasUnit: string = 'days',
    returnOnlyTime: boolean = false
  ): Date | string | null {
    if (sasValue === undefined) sasValue = ''
    if (typeof sasValue !== 'string') sasValue = sasValue.toString()

    if (sasValue.length === 0) {
      if (sasUnit === 'days') return null
      if (sasUnit === 'seconds') {
        if (returnOnlyTime) {
          return '11:00:00'
        } else {
          return null
        }
      }
    }

    let jsDate = this.helperService.convertSasDaysToJsDate(sasValue, sasUnit)

    // If it's datetime value (formatted) we parse it, conversion is overridden
    if (sasValue.split(':').length === 4) {
      const sasValueSplit = sasValue.split(':')

      jsDate = new Date(sasValueSplit[0])
      jsDate.setHours(parseInt(sasValueSplit[1]))
      jsDate.setMinutes(parseInt(sasValueSplit[2]))
      jsDate.setSeconds(parseInt(sasValueSplit[3]))
    } else if (isNaN(Number(sasValue))) {
      // If it's date value (formatted) we parse it, conversion is overridden
      jsDate = new Date(sasValue)
    }

    let jsDateTime = `${this.helperService.addLeadingZero(
      jsDate.getHours().toString()
    )}:${this.helperService.addLeadingZero(
      jsDate.getMinutes().toString()
    )}:${this.helperService.addLeadingZero(jsDate.getSeconds().toString())}`

    return returnOnlyTime ? jsDateTime : jsDate
  }
}
