/**
* Service for setting dynamic window scaling.
*
* @module scaleService
* @see https://docs.angularjs.org/api/ng/type/angular.Module#service
*/
angular.module('tgaApp').service('scaleService', [
'$window', '$document', '$log', 'gameConfig', '$timeout', 'utilityService',
function scaleService(
$window, $document, $log, gameConfig, $timeout, utilityService,
) {
/**
* Initialize scale service, trigger scale recalculation and set listener
* for `window.resize`if not mobile. If mobile only trigger on orientation change.
*/
this.init = () => {
const { scale } = gameConfig;
if (scale) {
if (!utilityService.isMobile()) {
$window.addEventListener('resize', this.windowResize);
} else {
$window.addEventListener('orientationchange',
() => {
$timeout(() => {
this.windowResize();
}, 400);
});
}
$timeout(() => {
this.windowResize();
});
}
};
/**
* Trigger window scale recalculation.
*/
this.windowResize = () => {
const { height, width, element } = gameConfig.scale;
const desiredRatio = width / height;
const realWidth = $window.innerWidth;
const realHeight = $window.innerHeight;
const realRatio = realWidth / realHeight;
const scale = desiredRatio > realRatio ? realWidth / width : realHeight / height;
const e = $document[0].querySelector(element || 'body');
e.style.transform = `translate(-50%, -50%) scale(${scale})`;
e.style.position = 'absolute';
e.style.top = '50%';
e.style.left = '50%';
e.style.width = `${width}px`;
e.style.height = `${height}px`;
e.style.margin = '0';
};
},
]);