import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import { includes } from 'lodash';
var regExpOfZenkaku = /[！-～]/m; // ちょうど ASCII から 0xfee0 だけずれている Unicode

var pattersOfZenkaku = [// ずれ方に規則性がない [Unicode, ASCII]
["\u3000", " "], ["\u201D", "\""], ["\u2019", "'"], ["\u3001", ","], ["\u3002", "."], ["\u30FC", "-"], ["\u30FB", "/"], ["\u300C", "["], ["\u300D", "]"], ["\u300E", "{"], ["\u300F", "}"], ["\u301C", "~"]];
var specialCharas = /[\n!-/:-@\[-\^`{-~]/m;
/**
 * エラーを起こしそうな変更を事前に修正する. change を破壊的に変更する
 * @param change CodeMirror の 'beforeChange' に渡される change 引数
 * @returns どのような変更が行われたのかを表す結果
 */

export default function fixDangerousChange(change, removed) {
  if (change.update && (change.origin === '+input' || change.origin === '*compose')) {
    var flag = false; // 変換が行われたら true になる

    var replaced = change.text.map(function (text) {
      var converted = replaceZenkaku(text);
      flag = flag || converted !== text;
      return converted;
    });

    if (flag) {
      change.update(change.from, change.to, replaced);
      return {
        hankaku: true
      };
    }
  }

  if (change.cancel && removed && change.origin === '+delete') {
    if (specialCharas.test(removed)) {
      change.cancel();
      return {
        canceled: true
      };
    }
  }

  return {};
}

function replaceZenkaku(text) {
  if (regExpOfZenkaku.test(text)) {
    var globalRegExp = new RegExp(regExpOfZenkaku, 'g');
    text = text.replace(globalRegExp, function (s) {
      return String.fromCharCode(s.charCodeAt(0) - 0xfee0);
    });
  }

  for (var _i = 0; _i < pattersOfZenkaku.length; _i++) {
    var _pattersOfZenkaku$_i = _slicedToArray(pattersOfZenkaku[_i], 2),
        before = _pattersOfZenkaku$_i[0],
        after = _pattersOfZenkaku$_i[1];

    if (includes(text, before)) {
      text = text.split(before).join(after);
    }
  }

  return text;
}