import JSON5 from 'json5'
import {isPathType} from "./index";

export interface IPanel {
  type: string;
  payload?: any;
  isCollapsed?: boolean;
}

const COLLAPSE_SYMBOL = '~'
const PARAMS_SYMBOL = ';'

export function stackToHash(stack: IPanel[]) {
  const hash = stack.map(panel => {
    let json = JSON5.stringify(panel.payload || {});
    json = json.substring(1, json.length - 1); // Remove the outer {}
    return `${panel.type}${panel.isCollapsed ? COLLAPSE_SYMBOL : ''}${json ? PARAMS_SYMBOL : ''}${json}`;
  }).join(isPathType() ? '/' : '&');
  return isPathType() ? `/${hash}` : `#${hash}`;
}


export function hashToStack(hash: string|undefined): IPanel[] {
  let stack:IPanel[] = [];
  const str = hash.replace(isPathType() ? /^\// : /^#/, '');
  if (str) {
    stack = str.split(isPathType() ? '/' : '&').map(item => {
      if (!item.includes(PARAMS_SYMBOL)) {
        return { type: item.replace(COLLAPSE_SYMBOL, ''), isCollapsed: item.includes(COLLAPSE_SYMBOL), payload: {} };
      }
      const [type, payload] = item.split(PARAMS_SYMBOL);
      const isCollapsed = type.includes(COLLAPSE_SYMBOL);
      let payloadObj:any = {};
      try {
        let json = decodeURIComponent(payload);
        if (!json.startsWith('{')) {
          json = `{${json}`; // Ensure it starts with a '{' to be valid JSON
        }
        if (!json.endsWith('}')) {
          json += '}'; // Ensure it ends with a '}' to be valid JSON
        }
        payloadObj = JSON5.parse(json);
      } catch (e) {
        // ignore
        console.warn(`Error parsing payload for type ${type}:`, payload, e);
      }
      return {
        type: type.replace(COLLAPSE_SYMBOL, ''),
        isCollapsed,
        payload: payloadObj
      };
    });
  }
  return stack;
}
