/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
/* jshint node:true */
'use strict';

var math = require('./math');

module.exports = DeviceOrientationCollector;

var deviceOrientationX_, deviceOrientationY_, deviceOrientationZ_;
var collectEntropy_ = function() {};

function DeviceOrientationCollector(collectEntropyCallback) {
  collectEntropy_ = collectEntropyCallback;
}

DeviceOrientationCollector.prototype = {
  handleEvent: function(ev) {
    ev = ev || window.event;
    var currentX =
        (math.entropyRound(ev.gamma) || math.entropyRound(ev.x) || 0);
    var currentY = (math.entropyRound(ev.beta) || math.entropyRound(ev.y) || 0);
    var currentZ =
        (math.entropyRound(ev.alpha) || math.entropyRound(ev.z) || 0);
    // The API detects and delivers accelerometer data 50 times per
    // second
    // even if there is any event related, so this is
    // a way to control if it really changed or not
    if ((deviceOrientationX_ === null) || (deviceOrientationY_ === null) ||
        (deviceOrientationZ_ === null) || (deviceOrientationX_ !== currentX) ||
        (deviceOrientationY_ !== currentY) ||
        (deviceOrientationZ_ !== currentZ)) {
      deviceOrientationX_ = currentX;
      deviceOrientationY_ = currentY;
      deviceOrientationZ_ = currentZ;
      collectEntropy_(
          currentX + currentY + currentZ + (+new Date()), 1);
    }
  }
};

