// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
/**
 * CodeMirror 折叠 Gutter 扩展（行号旁折叠按钮）
 * 依赖 foldcode 模块，在 gutter 区域显示折叠/展开标识，支持点击触发折叠操作
 */
(function(mod) {
  if (typeof exports == "object" && typeof module == "object") // CommonJS
    mod(require("../../lib/codemirror"), require("./foldcode"));
  else if (typeof define == "function" && define.amd) // AMD
    define(["../../lib/codemirror", "./foldcode"], mod);
  else // Plain browser env
    mod(CodeMirror);
})(function(CodeMirror) {
  "use strict";
  /**
   * 定义“foldGutter”配置项（控制折叠 gutter 功能）
   * @param {CodeMirror} cm - 编辑器实例
   * @param {boolean/object} val - 配置值（false=关闭；true=默认配置；object=自定义配置）
   * @param {boolean/object} old - 旧配置（用于初始化时的对比）
   */
  CodeMirror.defineOption("foldGutter", false, function(cm, val, old) {
    if (old && old != CodeMirror.Init) {
      cm.clearGutter(cm.state.foldGutter.options.gutter);
      cm.state.foldGutter = null;
      cm.off("gutterClick", onGutterClick);
      cm.off("change", onChange);
      cm.off("viewportChange", onViewportChange);
      cm.off("fold", onFold);
      cm.off("unfold", onFold);
      cm.off("swapDoc", updateInViewport);
    }
    if (val) {
      cm.state.foldGutter = new State(parseOptions(val));
      updateInViewport(cm);
      cm.on("gutterClick", onGutterClick);
      cm.on("change", onChange);
      cm.on("viewportChange", onViewportChange);
      cm.on("fold", onFold);
      cm.on("unfold", onFold);
      cm.on("swapDoc", updateInViewport);
    }
  });

  var Pos = CodeMirror.Pos;
  /**
   * 折叠 gutter 状态类（存储配置和可视区域范围）
   * @param {Object} options - 折叠 gutter 配置项
   */
  function State(options) {
    this.options = options;
    this.from = this.to = 0;
  }
  /**
   * 解析折叠 gutter 配置（补全默认值）
   * @param {boolean/object} opts - 输入配置
   * @return {Object} 完整配置对象
   */
  function parseOptions(opts) {
    if (opts === true) opts = {};
    if (opts.gutter == null) opts.gutter = "CodeMirror-foldgutter";
    if (opts.indicatorOpen == null) opts.indicatorOpen = "CodeMirror-foldgutter-open";
    if (opts.indicatorFolded == null) opts.indicatorFolded = "CodeMirror-foldgutter-folded";
    return opts;
  }
  /**
   * 判断指定行是否已折叠（仅判断行首的折叠标记）
   * @param {CodeMirror} cm - 编辑器实例
   * @param {number} line - 行号
   * @return {boolean} 已折叠返回 true，否则 false
   */
  function isFolded(cm, line) {
    var marks = cm.findMarksAt(Pos(line));
    for (var i = 0; i < marks.length; ++i)
      if (marks[i].__isFold && marks[i].find().from.line == line) return true;
  }
  /**
   * 创建折叠标识元素（根据配置生成 DOM 元素）
   * @param {string/HTMLElement} spec - 标识配置（类名字符串或 DOM 元素）
   * @return {HTMLElement} 折叠标识 DOM 元素
   */
  function marker(spec) {
    if (typeof spec == "string") {
      var elt = document.createElement("div");
      elt.className = spec + " CodeMirror-guttermarker-subtle";
      return elt;
    } else {
      return spec.cloneNode(true);
    }
  }
   /**
   * 更新指定行范围的折叠标识（为每行设置对应的展开/折叠按钮）
   * @param {CodeMirror} cm - 编辑器实例
   * @param {number} from - 起始行号
   * @param {number} to - 结束行号（不含）
   */
  function updateFoldInfo(cm, from, to) {
    var opts = cm.state.foldGutter.options, cur = from;
    var minSize = cm.foldOption(opts, "minFoldSize");
    var func = cm.foldOption(opts, "rangeFinder");
    cm.eachLine(from, to, function(line) {
      var mark = null;
      if (isFolded(cm, cur)) {
        mark = marker(opts.indicatorFolded);
      } else {
        var pos = Pos(cur, 0);
        var range = func && func(cm, pos);
        if (range && range.to.line - range.from.line >= minSize)
          mark = marker(opts.indicatorOpen);
      }
      cm.setGutterMarker(line, opts.gutter, mark);
      ++cur;
    });
  }
  /**
   * 更新可视区域的折叠标识（仅处理当前可见的行）
   * @param {CodeMirror} cm - 编辑器实例
   */
  function updateInViewport(cm) {
    var vp = cm.getViewport(), state = cm.state.foldGutter;
    if (!state) return;
    cm.operation(function() {
      updateFoldInfo(cm, vp.from, vp.to);
    });
    state.from = vp.from; state.to = vp.to;
  }
  /**
   * Gutter 点击事件处理（点击折叠按钮触发折叠/展开）
   * @param {CodeMirror} cm - 编辑器实例
   * @param {number} line - 点击的行号
   * @param {string} gutter - 点击的 gutter 类名
   */
  function onGutterClick(cm, line, gutter) {
    var state = cm.state.foldGutter;
    if (!state) return;
    var opts = state.options;
    if (gutter != opts.gutter) return;
    cm.foldCode(Pos(line, 0), opts.rangeFinder);
  }

  function onChange(cm) {
    var state = cm.state.foldGutter;
    if (!state) return;
    var opts = state.options;
    state.from = state.to = 0;
    clearTimeout(state.changeUpdate);
    state.changeUpdate = setTimeout(function() { updateInViewport(cm); }, opts.foldOnChangeTimeSpan || 600);
  }
  /**
   * 视图区域变化事件处理（滚动/缩放时更新折叠标识）
   * @param {CodeMirror} cm - 编辑器实例
   */
  function onViewportChange(cm) {
    var state = cm.state.foldGutter;
    if (!state) return;
    var opts = state.options;
    clearTimeout(state.changeUpdate);
    state.changeUpdate = setTimeout(function() {
      var vp = cm.getViewport();
      if (state.from == state.to || vp.from - state.to > 20 || state.from - vp.to > 20) {
        updateInViewport(cm);
      } else {
        cm.operation(function() {
          if (vp.from < state.from) {
            updateFoldInfo(cm, vp.from, state.from);
            state.from = vp.from;
          }
          if (vp.to > state.to) {
            updateFoldInfo(cm, state.to, vp.to);
            state.to = vp.to;
          }
        });
      }
    }, opts.updateViewportTimeSpan || 400);
  }

  function onFold(cm, from) {
    var state = cm.state.foldGutter;
    if (!state) return;
    var line = from.line;
    if (line >= state.from && line < state.to)
      updateFoldInfo(cm, line, line + 1);
  }
});
