import React from "react";
import { Loader } from '../components/Loader';

export function insertSpinnersInString(template: string, separator = <Loader scale={0.4} isInline />): JSX.Element {
  const parts = template.split(/\{.*?\}/);

  return <>{parts.map((part, i) => part.trim().length > 0 && i + 1 < parts.length ? <React.Fragment key={i}>{part}{separator}</React.Fragment> : part)}</>;
}

export const PARAM_SEPARATOR = "::";
export const DEFAULT_URL_TEXT = "see details";

export function insertLinksAndSpinnersInString(template: string, policyUrl: string | undefined, marketUrl: string | undefined, separator = <Loader scale={0.4} isInline />): JSX.Element {
  const items = [...template.matchAll(/\{([^{}]*)\}/g)].map(item => item[1]);

  const parts = template.split(/\{.*?\}/);

  const replacer = (
    item: string,
    extText: string,
    index: number,
    templateItems: string[],
    extTextList: string[],
  ) => {
    const itemParts = item.split(PARAM_SEPARATOR);

    switch (itemParts[0]) {
      case "marketAtomicaUrl":
        return <React.Fragment key={index}>
            {marketUrl &&
              <a
                href={marketUrl}
                target="_blank"
                rel="noreferrer"
                className={'link-button'}
              >
                {itemParts[1] ?? DEFAULT_URL_TEXT}
              </a>
            }
            {extText}
          </React.Fragment>;

      case "policyAtomicaUrl":
        return <React.Fragment key={index}>
            {policyUrl &&
              <a
                href={policyUrl}
                target="_blank"
                rel="noreferrer"
                className={'link-button'}
              >
                {itemParts[1] ?? DEFAULT_URL_TEXT}
              </a>
            }
            {extText}
          </React.Fragment>;

      default:
        return extText?.trim().length > 0 || index + 2 === extTextList.length ?
          <React.Fragment key={index}>{separator}{extText}</React.Fragment> :
          extText;
    }
  };

  return <>{[parts[0], ...items.map((item, index) => replacer(item, parts[index + 1], index, items, parts))]}</>;
}

export function parseQuery<T>(queryString: string) {
  const query: any = {};
  const pairs = (queryString[0] === "?" ? queryString.substring(1) : queryString).split("&");

  for (let i = 0; i < pairs.length; i++) {
    const pair = pairs[i].split("=");
    query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || "");
  }

  return query as T;
}