import { IGenericTimePicker } from '../../../generic/types';
import { ISlackInput, ISlackTextObject, ISlackTimePicker } from '../../types';
import { transformTextObject } from './text';
import { transformConfirm } from './confirm';
import { getElementWithSectionWrapper } from '../helpers/section-wrapper';

export const transformTimePicker = ({
  props
}: IGenericTimePicker): ISlackTimePicker|ISlackInput => {
  const element: ISlackTimePicker = {
    type: 'timepicker',
    action_id: props.slack?.action_id || props.variableName || props.web?.variableName
  };

  if (props.placeholder) {
    element.placeholder = transformTextObject({
      value: props.placeholder,
      slack: {
        type: props.slack?.placeholder_type || 'mrkdwn',
        emoji: props.slack?.placeholder_emoji,
        verbatim: props.slack?.placeholder_verbatim
      }
    });
  }

  if (props.value) {
    const convertTime = (timeValue) => {
      let hours, minutes;
      if (typeof timeValue === 'string') {
        const [time, mod] = timeValue.split(' ');

        const modifier = (mod === 'am') ? 'am' : 'pm';
  
        [hours, minutes] = time.split(':');
  
        if (hours === '12') {
          hours = '00';
        }
        

        if (modifier === 'pm') {
          hours = parseInt(hours, 10) + 12;
        }
      } else {
        // support OrTimePicker values
        hours = timeValue?.HH || '00';
        minutes = timeValue?.mm || '00';
      }

      return `${hours}:${minutes}`;
    };

    element.initial_time = convertTime(props.value);
  }

  const confirm = props.slack?.confirm;

  if (confirm) {
    element.confirm = transformConfirm(confirm);
  }

  if (props.label) {
    const label: ISlackTextObject = transformTextObject({
      value: props.label,
      type: 'plain'
    });

    const dispatch_action = props.web?.interactive;

    return getElementWithSectionWrapper(element, label, dispatch_action);
  }

  return element;
};
