/*! Based On NoSleep.js v0.12.0 - git.io/vfn01 - Rich Tibbett - MIT license */

class PromiseCompleter {
  _promise;
  _resolve;
  _reject;
  constructor() {
    this._promise = new Promise((resolve, reject) => {
      this._resolve = resolve;
      this._reject = reject;
    });
  }

  isCompleted = false;

  get future() {
    return this._promise;
  }

  complete(value) {
    this.isCompleted = true;
    this._resolve(value);
  }

  completeError(error) {
    this._reject(error);
  }
}

var webm =
  'data:video/webm;base64,GkXfo0AgQoaBAUL3gQFC8oEEQvOBCEKCQAR3ZWJtQoeBAkKFgQIYU4BnQI0VSalmQCgq17FAAw9CQE2AQAZ3aGFtbXlXQUAGd2hhbW15RIlACECPQAAAAAAAFlSua0AxrkAu14EBY8WBAZyBACK1nEADdW5khkAFVl9WUDglhohAA1ZQOIOBAeBABrCBCLqBCB9DtnVAIueBAKNAHIEAAIAwAQCdASoIAAgAAUAmJaQAA3AA/vz0AAA='
var mp4 =
  'data:video/mp4;base64,[encoded data, 6456 characters]'

var _createClass = (function () {
  function defineProperties(target, props) {
    for (var i = 0; i < props.length; i++) {
      var descriptor = props[i]
      descriptor.enumerable = descriptor.enumerable || false
      descriptor.configurable = true
      if ('value' in descriptor) descriptor.writable = true
      Object.defineProperty(target, descriptor.key, descriptor)
    }
  }
  return function (Constructor, protoProps, staticProps) {
    if (protoProps) defineProperties(Constructor.prototype, protoProps)
    if (staticProps) defineProperties(Constructor, staticProps)
    return Constructor
  }
})()

function _classCallCheck(instance, Constructor) {
  if (!(instance instanceof Constructor)) {
    throw new TypeError('Cannot call a class as a function')
  }
}

// Detect native Wake Lock API support
var nativeWakeLock = 'wakeLock' in navigator

var NoSleep = (function () {
  var _playVideoCompleter;

  function NoSleep() {
    var _this = this

    _classCallCheck(this, NoSleep)

    this.nativeEnabled = false
    if (nativeWakeLock) {
      this._nativeRequested = false
      this._wakeLock = null
      this._wakeLockRequest = null
      this._wakeLockRelease = null
      this._wakeLockReleaseSentinel = null
      this._wakeLockReplacement = null
      var handleVisibilityChange = function handleVisibilityChange() {
        if (_this._nativeRequested && document.visibilityState === 'visible') {
          _this._requestNativeWakeLock().catch(function () {})
        }
      }
      document.addEventListener('visibilitychange', handleVisibilityChange)
      document.addEventListener('fullscreenchange', handleVisibilityChange)
    } else {
      // Set up no sleep video element
      this.noSleepVideo = document.createElement('video')

      this.noSleepVideo.setAttribute('title', 'No Sleep')
      this.noSleepVideo.setAttribute('playsinline', '')

      this._addSourceToVideo(this.noSleepVideo, 'webm', webm)
      this._addSourceToVideo(this.noSleepVideo, 'mp4', mp4)

      this.noSleepVideo.addEventListener('loadedmetadata', function () {
        if (_this.noSleepVideo.duration <= 1) {
          // webm source
          _this.noSleepVideo.setAttribute('loop', '')
        } else {
          // mp4 source
          _this.noSleepVideo.addEventListener('timeupdate', function () {
            if (_this.noSleepVideo.currentTime > 0.5) {
              _this.noSleepVideo.currentTime = Math.random()
            }
          })
        }
      })
    }
  }

  _createClass(NoSleep, [
    {
      key: '_addSourceToVideo',
      value: function _addSourceToVideo(element, type, dataURI) {
        var source = document.createElement('source')
        source.src = dataURI
        source.type = 'video/' + type
        element.appendChild(source)
      },
    },
    {
      key: '_releaseNativeWakeLock',
      value: function _releaseNativeWakeLock(wakeLock) {
        var _this2 = this

        if (this._wakeLockRelease !== null) {
          if (this._wakeLockReleaseSentinel === wakeLock) {
            return this._wakeLockRelease
          }
          return this._wakeLockRelease
            .catch(function () {})
            .then(function () {
              return _this2._releaseNativeWakeLock(wakeLock)
            })
        }

        var release = Promise.resolve()
          .then(function () {
            return wakeLock.release()
          })
          .then(function () {
            if (_this2._wakeLock === wakeLock) {
              _this2._wakeLock = null
              _this2.nativeEnabled = false
            }
          })
          .finally(function () {
            if (_this2._wakeLockRelease === release) {
              _this2._wakeLockRelease = null
              _this2._wakeLockReleaseSentinel = null
            }
          })
        this._wakeLockReleaseSentinel = wakeLock
        this._wakeLockRelease = release
        return release
      },
    },
    {
      key: '_requestNativeWakeLock',
      value: function _requestNativeWakeLock(afterRelease) {
        var _this3 = this

        if (
          !this._nativeRequested ||
          document.visibilityState !== 'visible'
        ) {
          return Promise.resolve()
        }
        if (!afterRelease && this._wakeLockReplacement !== null) {
          return this._wakeLockReplacement
        }
        if (this._wakeLock !== null) {
          if (
            this._wakeLockRelease !== null &&
            this._wakeLockReleaseSentinel === this._wakeLock
          ) {
            var replacement
            replacement = this._wakeLockRelease
              .then(function () {
                return _this3._requestNativeWakeLock(true)
              })
              .finally(function () {
                if (_this3._wakeLockReplacement === replacement) {
                  _this3._wakeLockReplacement = null
                }
              })
            this._wakeLockReplacement = replacement
            return replacement
          }
          return Promise.resolve()
        }
        if (this._wakeLockRequest !== null) {
          return this._wakeLockRequest
        }

        var acquisition
        acquisition = navigator.wakeLock
          .request('screen')
          .then(function (wakeLock) {
            wakeLock.addEventListener('release', function () {
              if (_this3._wakeLock === wakeLock) {
                _this3._wakeLock = null
                _this3.nativeEnabled = false
                if (
                  _this3._nativeRequested &&
                  document.visibilityState === 'visible'
                ) {
                  _this3._requestNativeWakeLock().catch(function () {})
                }
              }
            })

            if (!_this3._nativeRequested) {
              _this3._wakeLock = wakeLock
              _this3.nativeEnabled = true
              return _this3._releaseNativeWakeLock(wakeLock)
            }

            _this3._wakeLock = wakeLock
            _this3.nativeEnabled = true
          })
          .catch(function (err) {
            throw err.name + ', ' + err.message
          })
          .finally(function () {
            if (_this3._wakeLockRequest === acquisition) {
              _this3._wakeLockRequest = null
            }
          })
        this._wakeLockRequest = acquisition
        return acquisition
      },
    },
    {
      key: 'enable',
      value: async function enable() {
        if (nativeWakeLock) {
          this._nativeRequested = true
          return this._requestNativeWakeLock()
        } else {
          if (_playVideoCompleter == null) {
            _playVideoCompleter = new PromiseCompleter()
          }
          var playPromise = this.noSleepVideo.play()
          playPromise.then(function (res) {
            _playVideoCompleter.complete()
            _playVideoCompleter = null
          }).catch(function (err) {
            var errorMessage = err.name + ', ' + err.message
            _playVideoCompleter.completeError(errorMessage)
            _playVideoCompleter = null
          });
          return _playVideoCompleter.future
        }
      },
    },
    {
      key: 'disable',
      value: async function disable() {
        if (nativeWakeLock) {
          this._nativeRequested = false

          var acquisition = this._wakeLockRequest
          if (acquisition !== null) {
            try {
              await acquisition
            } catch (_) {
              // A disable supersedes any failed acquisition.
            }
          }

          var wakeLock = this._wakeLock
          if (wakeLock !== null) {
            await this._releaseNativeWakeLock(wakeLock)
          }

          if (this._nativeRequested) {
            await this._requestNativeWakeLock()
          }
        } else {
          if (_playVideoCompleter != null) {
            await _playVideoCompleter.future
          }
          this.noSleepVideo.pause()
        }
        return Promise.resolve();
      },
    },
    {
      key: 'isEnabled',
      value: async function isEnabled() {
        if (nativeWakeLock) {
          var acquisition = this._wakeLockRequest
          if (acquisition !== null) {
            try {
              await acquisition
            } catch (_) {
              return false
            }
          }
          return this.nativeEnabled
        } else {
          if (_playVideoCompleter != null) {
            await _playVideoCompleter.future
          }
          if (this.noSleepVideo == undefined) {
            return false
          }

          return !this.noSleepVideo.paused
        }
      },
    },
  ])

  return NoSleep
})()

var noSleep = new NoSleep()

var Wakelock = {
  enabled: async function () {
    try {
      return noSleep.isEnabled()
    } catch (e) {
      return false
    }
  },
  toggle: async function (enable) {
    try {
      if (enable) {
        await noSleep.enable()
      } else {
        await noSleep.disable()
      }
    } catch (e) {
      return Promise.reject(e);
    }
    return Promise.resolve()
  },
}

if (nativeWakeLock != true) {
  // The first non-native call sometimes throws an error, however,
  // the error does not leak the try-catch above. Therefore, this
  // is an easy fix that realiably works.
  Wakelock.enabled()
}
