/**
 * Copyright (c) Nicolas Gallagher.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 */
import { addEvent } from './addEvent';
import supportsDOM from './supportsDOM';
import supportsPointerEvent from './supportsPointerEvent';
export type Modality = 'keyboard' | 'mouse' | 'touch' | 'pen';
let activeModality = 'keyboard';
let modality = 'keyboard';
let previousModality;
let previousActiveModality;
let isEmulatingMouseEvents = false;
const listeners = new Set();
const KEYBOARD = 'keyboard';
const MOUSE = 'mouse';
const TOUCH = 'touch';
const BLUR = 'blur';
const CONTEXTMENU = 'contextmenu';
const FOCUS = 'focus';
const KEYDOWN = 'keydown';
const MOUSEDOWN = 'mousedown';
const MOUSEMOVE = 'mousemove';
const MOUSEOVER = 'mouseover';
const MOUSEUP = 'mouseup';
const POINTERDOWN = 'pointerdown';
const POINTERMOVE = 'pointermove';
const POINTEROVER = 'pointerover';
const SCROLL = 'scroll';
const SELECTIONCHANGE = 'selectionchange';
const TOUCHCANCEL = 'touchcancel';
const TOUCHMOVE = 'touchmove';
const TOUCHSTART = 'touchstart';
const VISIBILITYCHANGE = 'visibilitychange';
const captureOptions = {
  capture: true,
  passive: true
};
declare function restoreModality(): any;
declare function onBlurWindow(): any;
declare function onFocusWindow(): any;
declare function onKeyDown(event: any): any;
declare function onVisibilityChange(): any;
declare function onPointerish(event: any): any;

if (supportsDOM()) {
  addEvent(window, BLUR, onBlurWindow);
  addEvent(window, FOCUS, onFocusWindow); // Must be capture phase because 'stopPropagation' might prevent these
  // events bubbling to the document.

  addEvent(document, KEYDOWN, onKeyDown, captureOptions);
  addEvent(document, VISIBILITYCHANGE, onVisibilityChange, captureOptions);
  [POINTERDOWN, POINTERMOVE, POINTEROVER, // Fallbacks
  CONTEXTMENU, MOUSEDOWN, MOUSEMOVE, MOUSEOVER, MOUSEUP, SCROLL, SELECTIONCHANGE, TOUCHCANCEL, TOUCHMOVE, TOUCHSTART].forEach(eventType => {
    addEvent(document, eventType, onPointerish, captureOptions);
  });
}

declare function callListeners(): any;
declare export function getActiveModality(): Modality;
declare export function getModality(): Modality;
declare export function addModalityListener(listener: ({
  activeModality: Modality,
  modality: Modality,
}) => void): () => void;
declare export function testOnly_resetActiveModality(): void;