import { supportsColor, isBrowser } from './environment.js';
import { create as create$2 } from './set.js';
import { create } from './pair.js';
import { mapToStyleString, element, text, append, addEventListener } from './dom.js';
import { stringify } from './json.js';
import { create as create$1 } from './map.js';
import { enqueue } from './eventloop.js';
import { round } from './math.js';
import { BOLD, UNBOLD, BLUE, GREEN, GREY, RED, PURPLE, ORANGE, UNCOLOR, computeNoColorLoggingArgs, createModuleLogger as createModuleLogger$1 } from './logging.common.js';

/**
 * Isomorphic logging module with support for colors!
 *
 * @module logging
 */


/**
 * @type {Object<Symbol,pair.Pair<string,string>>}
 */
const _browserStyleMap = {
  [BOLD]: create('font-weight', 'bold'),
  [UNBOLD]: create('font-weight', 'normal'),
  [BLUE]: create('color', 'blue'),
  [GREEN]: create('color', 'green'),
  [GREY]: create('color', 'grey'),
  [RED]: create('color', 'red'),
  [PURPLE]: create('color', 'purple'),
  [ORANGE]: create('color', 'orange'), // not well supported in chrome when debugging node with inspector - TODO: deprecate
  [UNCOLOR]: create('color', 'black')
};

/**
 * @param {Array<string|Symbol|Object|number|function():any>} args
 * @return {Array<string|object|number>}
 */
/* c8 ignore start */
const computeBrowserLoggingArgs = (args) => {
  if (args.length === 1 && args[0]?.constructor === Function) {
    args = /** @type {Array<string|Symbol|Object|number>} */ (/** @type {[function]} */ (args)[0]());
  }
  const strBuilder = [];
  const styles = [];
  const currentStyle = create$1();
  /**
   * @type {Array<string|Object|number>}
   */
  let logArgs = [];
  // try with formatting until we find something unsupported
  let i = 0;
  for (; i < args.length; i++) {
    const arg = args[i];
    // @ts-ignore
    const style = _browserStyleMap[arg];
    if (style !== undefined) {
      currentStyle.set(style.left, style.right);
    } else {
      if (arg === undefined) {
        break
      }
      if (arg.constructor === String || arg.constructor === Number) {
        const style = mapToStyleString(currentStyle);
        if (i > 0 || style.length > 0) {
          strBuilder.push('%c' + arg);
          styles.push(style);
        } else {
          strBuilder.push(arg);
        }
      } else {
        break
      }
    }
  }
  if (i > 0) {
    // create logArgs with what we have so far
    logArgs = styles;
    logArgs.unshift(strBuilder.join(''));
  }
  // append the rest
  for (; i < args.length; i++) {
    const arg = args[i];
    if (!(arg instanceof Symbol)) {
      logArgs.push(arg);
    }
  }
  return logArgs
};
/* c8 ignore stop */

/* c8 ignore start */
const computeLoggingArgs = supportsColor
  ? computeBrowserLoggingArgs
  : computeNoColorLoggingArgs;
/* c8 ignore stop */

/**
 * @param {Array<string|Symbol|Object|number>} args
 */
const print = (...args) => {
  console.log(...computeLoggingArgs(args));
  /* c8 ignore next */
  vconsoles.forEach((vc) => vc.print(args));
};

/* c8 ignore start */
/**
 * @param {Array<string|Symbol|Object|number>} args
 */
const warn = (...args) => {
  console.warn(...computeLoggingArgs(args));
  args.unshift(ORANGE);
  vconsoles.forEach((vc) => vc.print(args));
};
/* c8 ignore stop */

/**
 * @param {Error} err
 */
/* c8 ignore start */
const printError = (err) => {
  console.error(err);
  vconsoles.forEach((vc) => vc.printError(err));
};
/* c8 ignore stop */

/**
 * @param {string} url image location
 * @param {number} height height of the image in pixel
 */
/* c8 ignore start */
const printImg = (url, height) => {
  if (isBrowser) {
    console.log(
      '%c                      ',
      `font-size: ${height}px; background-size: contain; background-repeat: no-repeat; background-image: url(${url})`
    );
    // console.log('%c                ', `font-size: ${height}x; background: url(${url}) no-repeat;`)
  }
  vconsoles.forEach((vc) => vc.printImg(url, height));
};
/* c8 ignore stop */

/**
 * @param {string} base64
 * @param {number} height
 */
/* c8 ignore next 2 */
const printImgBase64 = (base64, height) =>
  printImg(`data:image/gif;base64,${base64}`, height);

/**
 * @param {Array<string|Symbol|Object|number>} args
 */
const group = (...args) => {
  console.group(...computeLoggingArgs(args));
  /* c8 ignore next */
  vconsoles.forEach((vc) => vc.group(args));
};

/**
 * @param {Array<string|Symbol|Object|number>} args
 */
const groupCollapsed = (...args) => {
  console.groupCollapsed(...computeLoggingArgs(args));
  /* c8 ignore next */
  vconsoles.forEach((vc) => vc.groupCollapsed(args));
};

const groupEnd = () => {
  console.groupEnd();
  /* c8 ignore next */
  vconsoles.forEach((vc) => vc.groupEnd());
};

/**
 * @param {function():Node} createNode
 */
/* c8 ignore next 2 */
const printDom = (createNode) =>
  vconsoles.forEach((vc) => vc.printDom(createNode()));

/**
 * @param {HTMLCanvasElement} canvas
 * @param {number} height
 */
/* c8 ignore next 2 */
const printCanvas = (canvas, height) =>
  printImg(canvas.toDataURL(), height);

const vconsoles = create$2();

/**
 * @param {Array<string|Symbol|Object|number>} args
 * @return {Array<Element>}
 */
/* c8 ignore start */
const _computeLineSpans = (args) => {
  const spans = [];
  const currentStyle = new Map();
  // try with formatting until we find something unsupported
  let i = 0;
  for (; i < args.length; i++) {
    let arg = args[i];
    // @ts-ignore
    const style = _browserStyleMap[arg];
    if (style !== undefined) {
      currentStyle.set(style.left, style.right);
    } else {
      if (arg === undefined) {
        arg = 'undefined ';
      }
      if (arg.constructor === String || arg.constructor === Number) {
        // @ts-ignore
        const span = element('span', [
          create('style', mapToStyleString(currentStyle))
        ], [text(arg.toString())]);
        if (span.innerHTML === '') {
          span.innerHTML = '&nbsp;';
        }
        spans.push(span);
      } else {
        break
      }
    }
  }
  // append the rest
  for (; i < args.length; i++) {
    let content = args[i];
    if (!(content instanceof Symbol)) {
      if (content.constructor !== String && content.constructor !== Number) {
        content = ' ' + stringify(content) + ' ';
      }
      spans.push(
        element('span', [], [text(/** @type {string} */ (content))])
      );
    }
  }
  return spans
};
/* c8 ignore stop */

const lineStyle =
  'font-family:monospace;border-bottom:1px solid #e2e2e2;padding:2px;';

/* c8 ignore start */
class VConsole {
  /**
   * @param {Element} dom
   */
  constructor (dom) {
    this.dom = dom;
    /**
     * @type {Element}
     */
    this.ccontainer = this.dom;
    this.depth = 0;
    vconsoles.add(this);
  }

  /**
   * @param {Array<string|Symbol|Object|number>} args
   * @param {boolean} collapsed
   */
  group (args, collapsed = false) {
    enqueue(() => {
      const triangleDown = element('span', [
        create('hidden', collapsed),
        create('style', 'color:grey;font-size:120%;')
      ], [text('▼')]);
      const triangleRight = element('span', [
        create('hidden', !collapsed),
        create('style', 'color:grey;font-size:125%;')
      ], [text('▶')]);
      const content = element(
        'div',
        [create(
          'style',
          `${lineStyle};padding-left:${this.depth * 10}px`
        )],
        [triangleDown, triangleRight, text(' ')].concat(
          _computeLineSpans(args)
        )
      );
      const nextContainer = element('div', [
        create('hidden', collapsed)
      ]);
      const nextLine = element('div', [], [content, nextContainer]);
      append(this.ccontainer, [nextLine]);
      this.ccontainer = nextContainer;
      this.depth++;
      // when header is clicked, collapse/uncollapse container
      addEventListener(content, 'click', (_event) => {
        nextContainer.toggleAttribute('hidden');
        triangleDown.toggleAttribute('hidden');
        triangleRight.toggleAttribute('hidden');
      });
    });
  }

  /**
   * @param {Array<string|Symbol|Object|number>} args
   */
  groupCollapsed (args) {
    this.group(args, true);
  }

  groupEnd () {
    enqueue(() => {
      if (this.depth > 0) {
        this.depth--;
        // @ts-ignore
        this.ccontainer = this.ccontainer.parentElement.parentElement;
      }
    });
  }

  /**
   * @param {Array<string|Symbol|Object|number>} args
   */
  print (args) {
    enqueue(() => {
      append(this.ccontainer, [
        element('div', [
          create(
            'style',
            `${lineStyle};padding-left:${this.depth * 10}px`
          )
        ], _computeLineSpans(args))
      ]);
    });
  }

  /**
   * @param {Error} err
   */
  printError (err) {
    this.print([RED, BOLD, err.toString()]);
  }

  /**
   * @param {string} url
   * @param {number} height
   */
  printImg (url, height) {
    enqueue(() => {
      append(this.ccontainer, [
        element('img', [
          create('src', url),
          create('height', `${round(height * 1.5)}px`)
        ])
      ]);
    });
  }

  /**
   * @param {Node} node
   */
  printDom (node) {
    enqueue(() => {
      append(this.ccontainer, [node]);
    });
  }

  destroy () {
    enqueue(() => {
      vconsoles.delete(this);
    });
  }
}
/* c8 ignore stop */

/**
 * @param {Element} dom
 */
/* c8 ignore next */
const createVConsole = (dom) => new VConsole(dom);

/**
 * @param {string} moduleName
 * @return {function(...any):void}
 */
const createModuleLogger = (moduleName) => createModuleLogger$1(print, moduleName);

export { BLUE, BOLD, GREEN, GREY, ORANGE, PURPLE, RED, UNBOLD, UNCOLOR, VConsole, createModuleLogger, createVConsole, group, groupCollapsed, groupEnd, print, printCanvas, printDom, printError, printImg, printImgBase64, vconsoles, warn };
