/*
 * Copyright (c) 2015 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, document, tau */

/**
 * Main view module.
 * @requires {@link core/event}
 * @requires {@link SoundManager/helpers/ui}
 * @requires {@link SoundManager/models/soundProfiles}
 * @namespace SoundManager/views/main
 * @memberof SoundManager/views
 */
define({
    name: 'views/main',
    requires: [
        'core/event',
        'helpers/ui',
        'models/soundProfiles'
    ],
    def: function main(req) {
        'use strict';

        /**
         * Event module instance.
         * @type {Module}
         */
        var event = req.core.event,

            /**
             * Ui helper module instance.
             * @type {Module}
             */
            uiHelper = req.helpers.ui,

            /**
             * SoundProfiles module instance.
             * @type {Module}
             */
            soundProfiles = req.models.soundProfiles,

            /**
             * Reference to profiles list.
             * @type {HTMLElement}
             */
            profilesList = null,

            /**
             * Reference to 'add profile' button.
             * @type {HTMLElement}
             */
            addProfileButton = null,

            /**
             * Reference to the 'ok' button from the 'Add profile' popup.
             * @type {HTMLElement}
             */
            addButton = null,

            /**
             * Reference to the profile's name input field.
             * @type {HTMLElement}
             */
            nameInput = null,

            /**
             * Popup message.
             * @type {string}
             */
            ALREADY_EXISTS_MSG = 'Profile with the same name already exists';

        /**
         * Handles click event on profiles list items.
         * @param {event} ev
         * @fires 'profile.clicked'
         */
        function onProfileClick(ev) {
            var id = parseInt(ev.currentTarget.getAttribute('data-profile-id'),
                10);
            event.fire('profile.clicked', id);
            tau.changePage('#details');
        }

        /**
         * Handles click event on 'Set' buttons.
         * @param {event} ev
         */
        function onSetProfileClick(ev) {
            var profileId = ev.currentTarget.getAttribute('data-profile-id');
            soundProfiles.setActive(parseInt(profileId, 10));

            ev.stopPropagation();
            ev.preventDefault();
        }

        /**
         * Creates HTML content of profile list from template.
         */
        function createListContent() {
            var activeProfileId = soundProfiles.getActiveProfileId(),
                i = 0,
                profiles = soundProfiles.getProfiles(),
                profile = null,
                templateArguments = [];

            for (i = 0; i < profiles.length; i += 1) {
                profile = profiles[i];
                templateArguments.push({
                    title: profile.title,
                    id: profile.id,
                    isActive: profile.id === activeProfileId
                });
            }

            uiHelper.fillList(profilesList, templateArguments, 'listItem');
        }

        /**
         * Registers event listeners of list items events.
         */
        function bindListEvents() {
            var liElements = profilesList.getElementsByTagName('li'),
                i = 0,
                li = null,
                setButton = null;

            for (i = 0; i < liElements.length; i += 1) {
                li = liElements[i];
                setButton = li.querySelector('button');
                if (setButton) {
                    setButton.addEventListener('click', onSetProfileClick);
                }
                li.addEventListener('click', onProfileClick);
            }
        }

        /**
         * Loads profiles.
         */
        function loadProfiles() {
            createListContent();
            bindListEvents();
        }

        /**
         * Registers view event listeners.
         */
        function bindEvents() {
            addButton.addEventListener('click', function addProfileListener() {
                var name = nameInput.value.trim();

                if (name.length === 0) {
                    return;
                }

                tau.closePopup();
                if (soundProfiles.getProfileByTitle(name)) {
                    uiHelper.showMessagePopup(ALREADY_EXISTS_MSG);
                } else {
                    soundProfiles.createProfile(name);
                }
                nameInput.value = '';
            });

            addProfileButton.addEventListener('click', function onClick() {
                uiHelper.openPopup('addProfilePopup');
            });

            event.listeners({
                'models.soundProfiles.changed': loadProfiles
            });
        }

        /**
         * Initializes module.
         * @memberof SoundManager/views/main
         */
        function init() {
            profilesList = document.getElementById('profiles');
            addButton = document.getElementById('add');
            nameInput = document.getElementById('name');
            addProfileButton = document.getElementById('addProfileButton');
            loadProfiles();
            bindEvents();
        }

        return {
            init: init
        };
    }
});
