import { lowerFirstLetter } from '../../../helpers/stringHelpers';
import { Attributes, Service } from './types';

export const createXMLS = (
  service: Service,
  attributes: Attributes,
  wrappedAttributes?: Record<string, Attributes>[],
) => {
  const wrapper = service.wrapper ? service.wrapper : `${lowerFirstLetter(service.name)}Input`;
  return `<?xml version="1.0" encoding="utf-8"?>
    <soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
      <soap12:Body>
        <${service.name} xmlns="https://is.skaut.cz/">
          <${wrapper}>
            ${attributes.map(atr => `<${atr.name}>${atr.value}</${atr.name}>`).join('')}
            ${wrappedAttributes?.map(wrappedAttribute => {
              return Object.keys(wrappedAttribute).map(key => {
                const item = wrappedAttribute[key];
                return `<${key}>${item
                  .map(atr => `<${atr.name}>${atr.value}</${atr.name}>`)
                  .join('')}</${key}>`;
              });
            })}
          </${wrapper}>
        </${service.name}>
      </soap12:Body>
    </soap12:Envelope>`;
};

export const trimXML = (xml: string) => {
  const wrapper = 'soap:Body';
  const start = `<${wrapper}>`;
  const end = `</${wrapper}>`;

  return xml.substring(xml.indexOf(start) + start.length, xml.indexOf(end));
};
