import React from "react";
import { SvgXml, XmlProps } from "react-native-svg";

export type SvgProps = XmlProps & {
  size?: number;
  [key: string]: any;
};

export const Svg = (props: SvgProps) => {
  const { xml, size } = props;
  const svg = String(xml);

  if (!svg.startsWith("<svg")) return null;

  const replaceXml = (init: string, key: string, value: any) => {
    if (!value || !init.includes(key)) return init;

    let res = "";
    let index = 0;
    let matched = false;

    for (let i = 0; i < init.length; ) {
      const item = init[i];

      if (init[i - 1] === " " && item === key[0]) {
        if (init.slice(i).startsWith(`${key}="`)) {
          matched = true;
          i += `${key}=`.length;
        }
      }

      if (matched) {
        if (item === '"') {
          matched = false;
          res += `${key}="${
            Array.isArray(value) ? value[index++] || value.pop() : value
          }"`;
        }
      } else res += item;

      i++;
    }

    return res;
  };

  const getXml = () => {
    let res = svg;

    for (let i in props) res = replaceXml(res, i, (props as any)?.[i]);
    if (size) {
      res = replaceXml(res, "width", size);
      res = replaceXml(res, "height", size);
    }

    return res;
  };

  return <SvgXml xml={getXml()} />;
};
