import axios from 'axios';

import { BASE_SERVICE_URL } from '../../../constants/api';
import { UNAUTHORIZED_ERROR } from '../../../constants/custom';
import { createXMLS } from './createXMLS';
import { Attributes, Service } from './types';

export const request = (
  serviceName: string,
  serviceEntity: Service,
  attributes: Attributes,
  wrappedAttributes?: Record<string, Attributes>[],
) => {
  const xmls = createXMLS(serviceEntity, attributes, wrappedAttributes);
  return axios
    .post(`${BASE_SERVICE_URL}${serviceName}.asmx`, xmls, {
      headers: {
        'Content-Type': 'text/xml; charset=utf-8',
        SOAPAction: `https://is.skaut.cz/${serviceEntity.name}`,
      },
    })
    .then(response => response.data)
    .catch(error => {
      const msg = error.response;
      const startTag = '<soap:Text xml:lang="en">';
      const endTag = '</soap:Text>';
      if (msg && msg.data.includes(UNAUTHORIZED_ERROR)) {
        console.log(serviceEntity);
        throw UNAUTHORIZED_ERROR;
      }
      throw (
        msg &&
        msg.data.substring(msg.data.indexOf(startTag) + startTag.length, msg.data.indexOf(endTag))
      );
    });
};

export const getParam = (item: any, param: string) => {
  return item[param] ? (item[param][0].$ ? '' : item[param][0]) : '';
};

export const getByAttribute = (obj: any, attr: string) => {
  if (!!obj[attr] && obj[attr][0] !== '') {
    return obj[attr][0];
  }
};
