'use strict';

var _commonjsHelpers = require('../../_virtual/_commonjsHelpers.js');
var fs$1 = require('fs');
var Url = require('url');
require('path');
var phin_compiled = require('../phin/lib/phin.compiled.js');
var index = require('../parse-bmfont-ascii/index.js');
var index$1 = require('../parse-bmfont-xml/lib/index.js');
var index$2 = require('../parse-bmfont-binary/index.js');
var mime$1 = require('../mime/mime.js');
var isBinary$1 = require('./lib/is-binary.js');

var fs = fs$1;
var url = Url;
var request = phin_compiled.phin_compiled;
var parseASCII = index.parseBmfontAscii;
var parseXML = index$1.lib;
var readBinary = index$2.parseBmfontBinary;
var mime = mime$1.mime_1;
var noop = function() {};
var isBinary = isBinary$1.isBinary;

function parseFont(file, data, cb) {
  var result, binary;

  if (isBinary(data)) {
    if (typeof data === 'string') data = Buffer.from(data, 'binary');
    binary = true;
  } else data = data.toString().trim();

  try {
    if (binary) result = readBinary(data);
    else if (/json/.test(mime.lookup(file)) || data.charAt(0) === '{')
      result = JSON.parse(data);
    else if (/xml/.test(mime.lookup(file)) || data.charAt(0) === '<')
      result = parseXML(data);
    else result = parseASCII(data);
  } catch (e) {
    cb(e);
    cb = noop;
  }

  cb(null, result);
}

var loadBmfont = function loadFont(opt, cb) {
  cb = typeof cb === 'function' ? cb : noop;

  if (typeof opt === 'string') opt = { uri: opt, url: opt };
  else if (!opt) opt = {};

  var file = opt.uri || opt.url;
  
  function handleData(err, data) {
    if (err) return cb(err)
    parseFont(file, data.body || data, cb);
  }

  if (url.parse(file).host) {
    request(opt, handleData);
  } else {
    fs.readFile(file, opt, handleData);
  }
};

var bMFont = /*@__PURE__*/_commonjsHelpers.getDefaultExportFromCjs(loadBmfont);

module.exports = bMFont;
