/*
 * Copyright (c) 2014 Samsung Electronics Co., Ltd. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*global define, window, document, history*/

/**
 * Init page module
 */

define({
    name: 'views/initPage',
    requires: [
        'core/event',
        'core/template',
        'core/application',
        'views/stopWatchPage',
        'views/timerPage',
        'core/systeminfo'
    ],
    def: function viewsInitPage(req) {
        'use strict';

        /**
         * Event module object.
         */
        var e = req.core.event,

            /**
             * Application module object.
             */
            app = req.core.application,

            /**
             * Timer page module object.
             */
            timerPage = req.views.timerPage,

            /**
             * System info module object.
             */
            sysInfo = req.core.systeminfo,

            /**
             * Array of URLs to all of the images used in application.
             * @type {string[]}
             */
            imagesToPreload = [
                'img/stopwatch/10x15/0.png',
                'img/stopwatch/10x15/1.png',
                'img/stopwatch/10x15/2.png',
                'img/stopwatch/10x15/3.png',
                'img/stopwatch/10x15/4.png',
                'img/stopwatch/10x15/5.png',
                'img/stopwatch/10x15/6.png',
                'img/stopwatch/10x15/7.png',
                'img/stopwatch/10x15/8.png',
                'img/stopwatch/10x15/9.png',
                'img/stopwatch/34x51/0.png',
                'img/stopwatch/34x51/1.png',
                'img/stopwatch/34x51/2.png',
                'img/stopwatch/34x51/3.png',
                'img/stopwatch/34x51/4.png',
                'img/stopwatch/34x51/5.png',
                'img/stopwatch/34x51/6.png',
                'img/stopwatch/34x51/7.png',
                'img/stopwatch/34x51/8.png',
                'img/stopwatch/34x51/9.png',
                'img/stopwatch/14x51/colon.png',
                'img/timer/flip_black_big_bg_scaled_active.png',
                'img/timer/flip_black_big_bg_scaled.png',
                'img/timer/icon_del_active.png',
                'img/timer/icon_del.png',
                'img/timer/time_up_background.png',
                'img/lap.png',
                'img/pause.png',
                'img/play.png',
                'img/stop.png',
                'img/stopwatch.png',
                'img/timer.png'
            ];

        /**
         * Loads ui images.
         */
        function preloadImages() {
            var image = null,
                length = imagesToPreload.length,
                i = 0;

            for (i = 0; i < length; i += 1) {
                image = new window.Image();
                image.src = imagesToPreload[i];
            }
        }

        /**
         * Handles tizenhwkey event.
         * @param {Event} ev
         */
        function onHardwareKeysTap(ev) {
            var keyName = ev.keyName,
                page = document.getElementsByClassName('ui-page-active')[0],
                pageid = page ? page.id : '';
            if (keyName === 'back') {
                if (timerPage.isAlarmInvoked()) {
                    e.fire('visibility.change', {
                        hidden: true
                    });
                    app.exit();
                }
                if (pageid === 'stopwatch-page' || pageid === 'timer-page') {
                    e.fire('visibility.change', {
                        hidden: true
                    });
                    app.exit();
                } else {
                    history.back();
                }
            }
        }

        /**
         * Handles visibilitychange event.
         * @param {Event} ev
         */
        function onVisibilityChange(ev) {
            e.fire('visibility.change', ev);
        }

        /**
         * Handles core.systeminfo.battery.low event.
         */
        function onLowBattery() {
            app.exit();
        }

        /**
         * Handles keydown event on document element.
         * @param {Event} ev
         */
        function onKeyDown(ev) {
            if (ev.keyIdentifier.indexOf('Power') !== -1) {
                e.fire('device.powerOff');
            }
        }

        /**
         * Registers events.
         */
        function bindEvents() {
            document.addEventListener('keydown', onKeyDown);
            window.addEventListener('tizenhwkey', onHardwareKeysTap);
            document.addEventListener('visibilitychange', onVisibilityChange);
            sysInfo.listenBatteryLowState();
        }

        /**
         * Initializes module.
         */
        function init() {
            preloadImages();
            bindEvents();
            sysInfo.checkBatteryLowState();
        }

        e.listeners({
            'core.systeminfo.battery.low': onLowBattery
        });

        return {
            init: init
        };
    }

});
