/*
 * 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, tau, document, console*/

/**
 * Module popup.
 * @namespace FMRadio/views/popup
 * @memberof FMRadio/views
 */

define({
    name: 'views/popup',
    def: function viewsPopup() {
        'use strict';

        /**
         * Type of popup.
         * @enum {number}
         * @readonly
         * @memberof FMRadio/views/popup
         */
        var popupTypes = Object.freeze({
                SIMPLE: 0,
                TEXT: 1,
                PROGRESS: 2,
                INPUT: 3
            }),

            /**
             * Hidden class value.
             * @type {string}
             */
            hiddenClass = 'hidden',

            /**
             * Input error class value.
             * @type {string}
             */
            inputErrorClass = 'input-error',

            /**
             * Single button class value.
             * @type {string}
             */
            singleButtonPopupClass = 'center_title_1btn',

            /**
             * Double button class value.
             * @type {string}
             */
            doubleButtonPopupClass = 'center_title_2btn',

            /**
             * Function called after Yes button is clicked.
             * @type {function}
             */
            successCallback = null,

            /**
             * Function called after popup close.
             * @type {function}
             */
            closeCallback = null,

            /**
             * Function that validates input data.
             * @type {function}
             */
            validator = null,

            /**
             * Input error text.
             * @type {string}
             */
            inputErrorText = '',

            /**
             * Current page id.
             * @type {string}
             */
            page = '',

            /**
             * Minimum length of station name.
             * @type {number}
             * @const
             * @memberof FMRadio/views/popup
             */
            STATION_NAME_LENGTH_MIN = 1,

            /**
             * Maximum length of station name.
             * @type {number}
             * @const
             * @memberof FMRadio/views/popup
             */
            STATION_NAME_LENGTH_MAX = 10;

        /**
         * Setups popup buttons.
         * @param {object} popupData Values of the popup content.
         */
        function setupPopupButtons(popupData) {
            var popup = document.getElementById(page + '-popup'),
                btnYes = document.getElementById(page + '-popup-yes-btn'),
                btnNo = document.getElementById(page + '-popup-no-btn');

            tau.widget.Button(btnYes).value(popupData.btnYesText);
            if (popupData.btnNoText) {
                tau.widget.Button(btnNo).value(popupData.btnNoText);
                btnNo.classList.remove(hiddenClass);
                popup.classList.remove(singleButtonPopupClass);
                popup.classList.add(doubleButtonPopupClass);
            } else {
                btnNo.classList.add(hiddenClass);
                popup.classList.add(singleButtonPopupClass);
                popup.classList.remove(doubleButtonPopupClass);
            }
        }

        /**
         * Setups popup content.
         * @param {number} popupType Type of the popup to display.
         * @param {object} popupData Values of the popup content.
         */
        function setupPopupContent(popupType, popupData) {
            var title = document.getElementById(page + '-popup-title'),
                text = document.getElementById(page + '-popup-text'),
                progress = document.getElementById(page + '-popup-progress'),
                input = document.getElementById(page + '-popup-input'),
                inputContainer = document.getElementById(
                    page + '-popup-input-container');

            title.innerHTML = popupData.title;

            text.classList.add(hiddenClass);
            progress.classList.add(hiddenClass);
            inputContainer.classList.add(hiddenClass);

            switch (popupType) {
                case popupTypes.PROGRESS:
                    text.innerHTML = popupData.text;
                    tau.widget.ProgressBar(progress).value(0);
                    text.classList.remove(hiddenClass);
                    progress.classList.remove(hiddenClass);
                    break;
                case popupTypes.INPUT:
                    input.value = popupData.input;
                    inputContainer.classList.remove(hiddenClass);
                    break;
                default:
                    text.innerHTML = popupData.text;
                    text.classList.remove(hiddenClass);
            }
        }

        /**
         * Shows customized popup.
         * @param {string} pageId Id of the current page.
         * @param {number} popupType Type of the popup to display.
         * @param {object} popupData Values of the popup content.
         * @memberof FMRadio/views/popup
         */
        function showPopup(pageId, popupType, popupData) {
            var popup = document.getElementById(pageId + '-popup');

            if (typeof popupData.validator !== 'function') {
                console.warn('popupData.validator is not a function.');
            }

            page = pageId;
            successCallback = popupData.btnYesCallback;
            closeCallback = popupData.exitCallback;
            validator = popupData.validator;
            inputErrorText = popupData.inputErrorText;

            setupPopupButtons(popupData);
            setupPopupContent(popupType, popupData);

            tau.widget.Popup(popup).open();
        }

        /**
         * Invokes callback on popup close.
         */
        function onPopupClose() {
            if (closeCallback) {
                closeCallback();
            }
        }

        /**
         * Shows error text for input value.
         */
        function showInputError() {
            var text = document.getElementById(page + '-popup-text');

            text.classList.remove(hiddenClass);
            text.classList.add(inputErrorClass);
            text.innerHTML = inputErrorText;
        }

        /**
         * Hides error text for input value.
         */
        function hideInputError() {
            var text = document.getElementById(page + '-popup-text');

            text.classList.add(hiddenClass);
            text.classList.remove(inputErrorClass);
        }

        /**
         * Handles popup yes button click.
         */
        function popupYesClicked() {
            var popup = document.getElementById(page + '-popup'),
                input = document.getElementById(page + '-popup-input'),
                isValid = true;

            if (validator) {
                isValid = validator(input.value);
            }
            if (isValid) {
                if (successCallback) {
                    hideInputError();
                    successCallback(input.value);
                }
                tau.widget.Popup(popup).close();
            } else {
                showInputError();
            }
        }

        /**
         * Updates progress popup value.
         * @param {number} progressValue Progress value in percent.
         * @param {number} stationsFound Number of found stations.
         * @memberof FMRadio/views/popup
         */
        function updateProgress(progressValue, stationsFound) {
            var popup = document.getElementById(page + '-popup'),
                text = document.getElementById(page + '-popup-text'),
                progress = document.getElementById(page + '-popup-progress'),
                progressBar = tau.widget.ProgressBar(progress);

            text.innerHTML = 'Stations found: ' + stationsFound;
            progressBar.value(Math.floor(progressValue));
            if (progressValue === 100) {
                tau.widget.Popup(popup).close();
            }
        }

        /**
         * Validates input with name rules.
         * @param {string} input Input to validate.
         * @returns {boolean} Is input valid.
         * @memberof FMRadio/views/popup
         */
        function nameValidator(input) {
            if (input.length >= STATION_NAME_LENGTH_MIN &&
                    input.length <= STATION_NAME_LENGTH_MAX) {
                return true;
            }
            return false;
        }

        /**
         * Validates input with frequency rules.
         * @param {string} input Input to validate.
         * @returns {boolean} Is input valid.
         * @memberof FMRadio/views/popup
         */
        function frequencyValidator(input) {
            return !isNaN(input);
        }

        /**
         * Binds events.
         */
        function bindEvents() {
            var mainPopup = document.getElementById('main-page-popup'),
                stationsPopup = document.getElementById('stations-page-popup'),
                mainY = document.getElementById('main-page-popup-yes-btn'),
                statY = document.getElementById('stations-page-popup-yes-btn');

            mainPopup.addEventListener('popupafterclose', onPopupClose);
            stationsPopup.addEventListener('popupafterclose', onPopupClose);
            mainY.addEventListener('click', popupYesClicked);
            statY.addEventListener('click', popupYesClicked);
        }

        /**
         * Initializes module.
         * @memberof FMRadio/views/popup
         */
        function init() {
            bindEvents();
        }

        return {
            init: init,
            popupTypes: popupTypes,
            showPopup: showPopup,
            updateProgress: updateProgress,
            nameValidator: nameValidator,
            frequencyValidator: frequencyValidator,
            STATION_NAME_LENGTH_MIN: STATION_NAME_LENGTH_MIN,
            STATION_NAME_LENGTH_MAX: STATION_NAME_LENGTH_MAX
        };
    }
});
