'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _object_to_mode = require('./modes/object_to_mode');

var _object_to_mode2 = _interopRequireDefault(_object_to_mode);

var _is_click = require('./libs/is_click');

var _is_click2 = _interopRequireDefault(_is_click);

var _is_tap = require('./libs/is_tap');

var _is_tap2 = _interopRequireDefault(_is_tap);

var _features_at = require('./libs/features_at');

var _features_at2 = _interopRequireDefault(_features_at);

var _mode_handler = require('./libs/mode_handler');

var _mode_handler2 = _interopRequireDefault(_mode_handler);

var _constants = require('./constants');

var _constants2 = _interopRequireDefault(_constants);

var _dom = require('../../util/dom');

var _dom2 = _interopRequireDefault(_dom);

var _methodsUtil = require('../../../_util/methods-util');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

/**
 * @文件说明: 定义Draw绘图的事件
 * @创建人: pjtools@vip.qq.com
 * @创建时间: 2020-05-21 17:36:35
 */

var events = function events(ctx) {
  // 统一处理及转换Mode模式的作用域
  var modes = Object.keys(ctx.options.modes).reduce(function (mode, key) {
    mode[key] = (0, _object_to_mode2['default'])(ctx.options.modes[key]);
    return mode;
  }, {});

  // 记录鼠标单击时的时间
  var mouseDownInfo = {};
  // 记录Touch时的时间
  var touchStartInfo = {};
  // 当前激活的Mode模式名
  var _currentModeName = null;
  // 当前激活的Mode模式
  var currentMode = null;
  // 判断是否已进行事件监听
  var isEventsListeners = false;
  // 记录当前监听事件对象
  var listenersEvents = {};

  var events = {};

  // 定义拖拽Drag事件
  events.drag = function (e, isDrag) {
    if (isDrag({
      point: e.point,
      time: new Date().getTime()
    })) {
      currentMode.drag(e);
    } else {
      e.originalEvent.stopPropagation();
    }
  };

  // 扩展Mouse Drag拖拽事件
  events.mousedrag = function (e) {
    events.drag(e, function (endInfo) {
      return !(0, _is_click2['default'])(mouseDownInfo, endInfo);
    });
  };

  // 扩展Touch Drag拖拽事件
  events.touchdrag = function (e) {
    events.drag(e, function (endInfo) {
      return !(0, _is_tap2['default'])(touchStartInfo, endInfo);
    });
  };

  // 定义Mouse Down事件
  events.mousedown = function (e) {
    mouseDownInfo = {
      time: new Date().getTime(),
      point: e.point
    };
    var features = _features_at2['default'].click(e, null, ctx);
    e.featureTarget = features[0];
    currentMode.mousedown(e);
  };

  // 定义Mouse Move移动事件
  events.mousemove = function (e) {
    var button = e.originalEvent.buttons !== undefined ? e.originalEvent.buttons : e.originalEvent.which;
    if (button === 1) {
      return events.mousedrag(e);
    }
    var features = _features_at2['default'].click(e, null, ctx);
    e.featureTarget = features[0];
    currentMode.mousemove(e);
  };

  // 定义Mouse Up事件
  events.mouseup = function (e) {
    var features = _features_at2['default'].click(e, null, ctx);
    e.featureTarget = features[0];

    if ((0, _is_click2['default'])(mouseDownInfo, {
      point: e.point,
      time: new Date().getTime()
    })) {
      currentMode.click(e);
    } else {
      currentMode.mouseup(e);
    }
  };

  // 定义Mouse Over事件
  events.mouseover = function (e) {
    currentMode.mouseover(e);
  };

  // 定义Mouse Out事件
  events.mouseout = function (e) {
    currentMode.mouseout(e);
  };

  // 定义Touch Start事件
  events.touchstart = function (e) {
    e.originalEvent.preventDefault();
    touchStartInfo = {
      time: new Date().getTime(),
      point: e.point
    };
    var features = _features_at2['default'].touch(e, null, ctx);
    e.featureTarget = features[0];
    currentMode.touchstart(e);
  };

  // 定义Touch Move事件
  events.touchmove = function (e) {
    e.originalEvent.preventDefault();
    currentMode.touchmove(e);
    return events.touchdrag(e);
  };

  // 定义Touch End事件
  events.touchend = function (e) {
    e.originalEvent.preventDefault();
    var features = _features_at2['default'].touch(e, null, ctx);
    e.featureTarget = features[0];
    if ((0, _is_tap2['default'])(touchStartInfo, {
      time: new Date().getTime(),
      point: e.point
    })) {
      currentMode.tap(e);
    } else {
      currentMode.touchend(e);
    }
  };

  // 8 - Backspace
  // 46 - Delete
  var isKeyModeValid = function isKeyModeValid(code) {
    return !(code === 8 || code === 46 || code >= 48 && code <= 57);
  };

  // 定义Keydown事件
  events.keydown = function (e) {
    if (e.keyCode === 46) {
      e.preventDefault();
      currentMode.trash();
    } else if (isKeyModeValid(e.keyCode)) {
      currentMode.keydown(e);
    }
  };

  // 定义Keyup事件
  events.keyup = function (e) {
    if (isKeyModeValid(e.keyCode)) {
      currentMode.keyup(e);
    }
  };

  var api = {
    // 激活当前模式
    start: function start() {
      var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

      _currentModeName = ctx.options.defaultMode;
      currentMode = (0, _mode_handler2['default'])(modes[_currentModeName](ctx, options), ctx);
      currentMode.start();
    },


    // 更新模式
    changeMode: function changeMode(modename, nextModeOptions) {
      var eventOptions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};

      var modebuilder = modes[modename];
      if (modebuilder === undefined) {
        throw new Error('\u7ED8\u56FE\u6A21\u5F0F[' + modename + ']\u4E0D\u5B58\u5728.');
      }
      if (!currentMode) {
        var mode = modebuilder(ctx, {});
        _currentModeName = ctx.options.defaultMode;
        currentMode = (0, _mode_handler2['default'])(mode, ctx);
      }
      // 停止历史绘制模式
      currentMode.stop();
      // 判断是否待更新模式与当前模式不同，则重新实例化
      var isModeChange = false;
      if (_currentModeName !== modename) {
        var _mode = modebuilder(ctx, nextModeOptions);
        _currentModeName = modename;
        currentMode = (0, _mode_handler2['default'])(_mode, ctx);
        isModeChange = true;
      }
      // 驱动模式激活
      currentMode.start(nextModeOptions || {});
      // 设置模式切换的渲染状态
      ctx.store.setModeChangeRendering();
      // 渲染绘制的数据
      ctx.store.render();
      // 判断是否不执行驱动事件
      eventOptions && (0, _methodsUtil.isBooleanTrue)(eventOptions.silent) && (isModeChange = false);
      // 判断是否需要执行事件回调
      isModeChange && ctx.api.fire(_constants2['default'].events.MODE_CHANGE, { mode: modename });
    },


    // 设置绘图可活动操作的状态
    actionable: function actionable(actions) {
      var changed = false;
      var actionState = {
        // 是否可操作垃圾桶 - 删除
        trash: false,
        // 是否可操作 - 合并要素
        combineFeatures: false,
        // 是否可操作 - 拆分复合要素
        uncombineFeatures: false
      };
      Object.keys(actions).map(function (action) {
        if (actionState[action] === undefined) {
          return;
        }
        if (actionState[action] !== actions[action]) {
          changed = true;
        }
        actionState[action] = actions[action];
      });
      if (changed) {
        ctx.api.fire(_constants2['default'].events.ACTIONABLE, {
          mode: this.getMode(),
          actions: actionState
        });
      }
    },


    // 获取当前模式的名称
    currentModeName: function currentModeName() {
      return _currentModeName;
    },


    // 渲染当前模式的数据
    currentModeRender: function currentModeRender(geojson, push) {
      return currentMode.render(geojson, push);
    },


    // 获取当前模式名称
    getMode: function getMode() {
      return _currentModeName;
    },


    // 获取当前模式实例对象
    getCurrentModeInstance: function getCurrentModeInstance() {
      if (currentMode) {
        var modeHanler = currentMode.mode();
        return modeHanler && modeHanler.mode();
      }
      return null;
    },


    // 执行事件
    fire: function fire(name, event) {
      events[name] && events[name](event);
    },


    // 判断是否已添加绘图事件监听
    isLoadedEventListeners: function isLoadedEventListeners() {
      return isEventsListeners;
    },


    // 添加绘图事件监听
    addEventListeners: function addEventListeners() {
      // 判断是否已绑定绘图事件监听
      if (isEventsListeners) {
        return;
      }

      ctx.iMapApi.on('draw.mousedown.' + ctx.uid, 'mousedown', events.mousedown);
      ctx.iMapApi.on('draw.mousemove.' + ctx.uid, 'mousemove', events.mousemove);
      ctx.iMapApi.on('draw.mouseup.' + ctx.uid, 'mouseup', events.mouseup);
      ctx.iMapApi.on('draw.touchstart.' + ctx.uid, 'touchstart', events.touchstart);
      ctx.iMapApi.on('draw.touchmove.' + ctx.uid, 'touchmove', events.touchmove);
      ctx.iMapApi.on('draw.touchend.' + ctx.uid, 'touchend', events.touchend);
      ctx.iMapApi.on('draw.mouseover.' + ctx.uid, 'mouseover', events.mouseover);
      ctx.iMapApi.on('draw.mouseout.' + ctx.uid, 'mouseout', events.mouseout);
      listenersEvents['draw.keydown.' + ctx.uid] = _dom2['default'].onEventListener(ctx.container, 'keydown', events.keydown);
      listenersEvents['draw.keyup.' + ctx.uid] = _dom2['default'].onEventListener(ctx.container, 'keyup', events.keyup);

      isEventsListeners = true;
    },


    // 移除绘图事件监听
    removeEventListeners: function removeEventListeners() {
      if (!isEventsListeners) {
        return;
      }

      ctx.iMapApi.off('draw.mousedown.' + ctx.uid);
      ctx.iMapApi.off('draw.mousemove.' + ctx.uid);
      ctx.iMapApi.off('draw.mouseup.' + ctx.uid);
      ctx.iMapApi.off('draw.touchstart.' + ctx.uid);
      ctx.iMapApi.off('draw.touchmove.' + ctx.uid);
      ctx.iMapApi.off('draw.touchend.' + ctx.uid);
      ctx.iMapApi.off('draw.mouseover.' + ctx.uid);
      ctx.iMapApi.off('draw.mouseout.' + ctx.uid);
      Object.keys(listenersEvents).map(function (key) {
        listenersEvents[key].remove();
        delete listenersEvents[key];
      });

      isEventsListeners = false;
    },


    // 驱动激活Feature要素的删除
    trash: function trash(options) {
      currentMode.trash(options);
    },


    // 合并选中的Feature要素
    combineFeatures: function combineFeatures() {
      currentMode.combineFeatures();
    },


    // 拆分选中的复合要素
    uncombineFeatures: function uncombineFeatures() {
      currentMode.uncombineFeatures();
    }
  };

  return api;
};

exports['default'] = events;