/*
 * Copyright (c) 2012 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 document, history, window, app, App, tau */

(function strict() {
    'use strict';

    /**
     * App.Ui constructor.
     * @constructor
     */
    App.Ui = function Ui() {
        return;
    };

    App.Ui.prototype = {

        /**
         * Highlights button storage type.
         * @param {string} storageType
         */
        highlightStoragetype:  function highlightStoragetype(storageType) {
            var highlighted = document.getElementsByClassName(
                'storage-type-highlight'
            );

            if (highlighted[0] !== undefined) {
                highlighted[0].classList.remove('storage-type-highlight');
            }
            if (storageType === 'ALL') {
                document.getElementById('folder-type-all').classList
                    .add('storage-type-highlight');
            } else if (storageType === 'INTERNAL') {
                document.getElementById('folder-type-internal').classList
                    .add('storage-type-highlight');
            } else if (storageType === 'EXTERNAL') {
                document.getElementById('folder-type-external').classList
                    .add('storage-type-highlight');
            }
        },

        /**
         * Replaces HTML sensitive chars in the given string.
         * @param {string} str
         * @return {string}
         */
        escapeEncies: function escapeEncies(str) {
            var tagsToReplace = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;'
            };
            return String(str).replace(/[&<>\"]/g, function replace(tag) {
                return tagsToReplace[tag] || tag;
            });
        },

        /**
         * Shows folders list.
         * @param {string} type
         * @param {ContentDirectory[]} folders
         */
        showFolderList: function showFolderList(type, folders) {
            var fileList = document.getElementById('file-list'),
                str = '',
                escapedFolders = [],
                i = 0,
                elem = {},
                folderLength = folders.length;

            for (i = 0; i < folderLength; i += 1) {
                elem = {};
                if (folders[i].title) {
                    elem.title = this.escapeEncies(folders[i].title);
                }
                if (folders[i].storageType) {
                    elem.storageType = this.escapeEncies(
                        folders[i].storageType);
                }
                if (folders[i].directoryURI) {
                    elem.directoryURI = this.escapeEncies(
                        folders[i].directoryURI);
                }
                escapedFolders.push(elem);
            }

            fileList.innerHTML = '';
            str = app.ui.template.get('folderListItem',
                {folders: escapedFolders, type: type});
            fileList.innerHTML = str.trim() || '<li>No media files</li>';
            tau.widget.Listview(fileList).refresh();
        },

        /**
         * Shows items list and change page to items.
         * @param {Content[]} items
         */
        showItemsList: function showItemsList(items) {
            var itemsList = document.getElementById('items-list'),
                str = '',
                itemsEscaped = [],
                i = 0,
                length = items.length,
                element = null,
                item = null;


            for (i = 0; i < length; i += 1) {
                element = {};
                item = items[i];

                element.title = this.escapeEncies(item.title);
                element.type = this.escapeEncies(item.type);
                element.rating = this.escapeEncies(item.rating);

                itemsEscaped.push(element);
            }

            str = app.ui.template.get('itemsListItem', {items: itemsEscaped});
            itemsList.innerHTML = str;
            tau.widget.Listview(itemsList).refresh();
            tau.changePage('#items');
        },

        /**
         * Shows media details and change page to details.
         * @param {Array} properties
         */
        showMediaDetail: function showMediaDetail(properties) {
            var mediaDetails = document.getElementById('media-details'),
                str = '';

            str = app.ui.template.get('itemDetails', {properties: properties});
            mediaDetails.innerHTML = str;
            tau.widget.Listview(mediaDetails).refresh();
            tau.changePage('#detail');
        },

        /**
         * Parses details object to array of parameters.
         * @param {Array} item
         */
        parseDetailsObject: function parseDetailsObject(item) {
            var details = [];

            if (item) {
                details.push(
                    {name: 'Title', property:
                        this.escapeEncies(item.title)},
                    {name: 'Size', property: item.size + ' Bytes'},
                    {name: 'Type', property: item.type},
                    {name: 'Identifier', property: item.id},
                    {name: 'Item URI', property:
                        this.escapeEncies(item.contentURI)},
                    {name: 'MIME type', property: item.mimeType},
                    {name: 'Modified date', property: item.modifiedDate
                        .toLocaleString()},
                    {name: 'Description', property:
                        this.escapeEncies(item.description)},
                    {name: 'Rating', property: item.rating});
                if (item.type === 'IMAGE') {
                    details.push({name: 'Width', property: item.width},
                        {name: 'Height', property: item.height});
                    if (item.geolocation) {
                        details.push({name: 'Latitude', property:
                                item.geolocation.latitude},
                            {name: 'Longitude', property:
                                item.geolocation.longitude});
                    }
                } else if (item.type === 'VIDEO') {
                    details.push({name: 'Width', property: item.width},
                        {name: 'Height', property: item.height},
                        {name: 'Album', property:
                            this.escapeEncies(item.album)},
                        {name: 'Artist', property:
                            this.escapeEncies(item.artists[0])},
                        {name: 'Duration', property:
                            item.duration + ' Milliseconds'});
                } else if (item.type === 'AUDIO') {
                    details.push({name: 'Album', property:
                            this.escapeEncies(item.album)},
                        {name: 'Artist', property:
                            this.escapeEncies(item.artists[0])},
                        {name: 'Composer', property:
                            this.escapeEncies(item.composers[0])},
                        {name: 'Genre', property: item.genres[0]},
                        {name: 'Copyright', property: item.copyright},
                        {name: 'Bitrate', property:
                            item.bitrate + ' Bps'},
                        {name: 'Track number', property:
                            item.trackNumber},
                        {name: 'Duration', property:
                            item.duration + ' Milliseconds'});
                }
            }
            return details;
        },

        /**
         * Adds events.
         */
        addEvents: function addEvents() {

            this.lastItemType = 'ALL';
            /**
             * Handles Tizen WH key event.
             * Backs page or closes application.
             * @param {HWKeyEvent} event
             */
            function onTizenHWKey(event) {
                if (event.keyName === 'back') {
                    if (tau.engine.getRouter().activePage.id === 'main') {
                        app.exit();
                    } else {
                        history.back();
                    }
                }
            }

            /**
             * Handles pagebeforeshow event on document.
             * Scrolls all pages to top.
             * @param {Event} event
             */
            function onPageBeforeShow(event) {
                event.target.getElementsByClassName('ui-content')[0]
                    .scrollTop = 0;
            }

            /**
             * Handles click event on folder list.
             * Gets folder lists and shows highlights button.
             * @param {Event} event
             */
            function onTypeClick(event) {
                var type = event.target.dataset.storageType;

                app.showFolderList(type);
                app.ui.highlightStoragetype(type);
            }

            /**
             * Handles click event on file list.
             * Shows selected folder items.
             * @param {Event} event
             */
            function onFileListClick(event) {
                var target = event.target,
                    id = null;

                if (target.tagName.toLowerCase() !== 'li') {
                    target = target.parentNode;
                }
                if (!target.dataset.id) {
                    return;
                }
                id = target.dataset.id;
                app.showFolderItems(Number(id), app.ui.lastItemType);
            }

            /**
             * Handles click event on items list.
             * Shows selected item details.
             * @param {Event} event
             */
            function onItemsListClick(event) {
                var target = event.target,
                    id = null,
                    item = [];

                if (target.tagName.toLowerCase() !== 'li') {
                    target = target.parentNode;
                }

                if (!target.dataset.id) {
                    return;
                }
                id = target.dataset.id;
                item = app.model.getDetailsItemById(id);
                app.ui.showMediaDetail(app.ui.parseDetailsObject(item));
            }

            /**
             * Handles change event on checkbox.
             * @param {Event} event
             */
            function onItemsListChange(event) {
                var checkbox = event.target;
                if (checkbox.checked === true) {
                    app.ui.lastItemType = checkbox.value;
                    app.showFolderItems(null, app.ui.lastItemType);
                }
            }

            /**
             * Handles pageinit event on items page.
             * Adds change listener to inputs.
             * @param {Event} event
             */
            function onItemsPageInit(event) {
                var inputs = event.target.getElementsByTagName('input'),
                    i = 0;

                for (i = inputs.length - 1; i >= 0; i -= 1) {
                    inputs[i].addEventListener('change', onItemsListChange);
                }
            }

            window.addEventListener('tizenhwkey', onTizenHWKey);
            document.addEventListener('pagebeforeshow', onPageBeforeShow);
            document.getElementById('items')
                .addEventListener('pageinit', onItemsPageInit);
            document.getElementById('folder-list')
                .addEventListener('click', onTypeClick);
            document.getElementById('file-list')
                .addEventListener('click', onFileListClick);
            document.getElementById('items-list')
                .addEventListener('click', onItemsListClick);
        }
    };
}());
