import { APIDecoder, APIResponse } from '@ucap-webmessenger/api';

export interface MailCountResponse {
  systemName: string;
  count: number;
}

export const decodeMailCount: APIDecoder<MailCountResponse> = (res: any) => {
  const domParser = new DOMParser();
  const dom: Document = domParser.parseFromString(res, 'text/xml');

  let count = 0;
  const countDom: HTMLCollection = dom.getElementsByTagName('COUNT');
  if (!!countDom && countDom.length > 0) {
    count =
      countDom[0].textContent.trim().length > 0
        ? Number(countDom[0].textContent.trim())
        : 0;
  }
  return {
    systemName: 'mailCount',
    count
  } as MailCountResponse;
};

export interface PaymentCountResponse {
  systemName: string;
  count: number;
}

export const decodePaymentCount: APIDecoder<PaymentCountResponse> = (
  res: any
) => {
  const domParser = new DOMParser();
  const dom: Document = domParser.parseFromString(res, 'text/xml');

  let count = 0;
  const viewentriesDom: HTMLCollection = dom.getElementsByTagName(
    'viewentries'
  );
  if (
    !!viewentriesDom &&
    viewentriesDom.length > 0 &&
    !!viewentriesDom[0].getAttribute('toplevelentries') &&
    viewentriesDom[0].getAttribute('toplevelentries').length > 0
  ) {
    count =
      viewentriesDom[0].getAttribute('toplevelentries').trim().length > 0
        ? Number(viewentriesDom[0].getAttribute('toplevelentries').trim())
        : 0;
  }

  return {
    systemName: 'paymentCount',
    count
  } as PaymentCountResponse;
};
