/*
 * 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.
 */

/*jslint devel: true*/
/*global Config, Model, Ui, tizen, setTimeout, navigator, app, window, Event */

var App = null;

(function strict() { // strict mode wrapper
    'use strict';

   /**
    * Creates a new application object
    *
    * @class Application
    */
    App = function App() {
        this.configData = {};
    };

    App.prototype = {
        /**
         * @type Array
         */
        requires: [
            'js/app.config.js',
            'js/app.model.js',
            'js/app.ui.js',
            'js/app.ui.templateManager.js',
            'js/app.ui.templateManager.modifiers.js',
            'js/app.helpers.js'
        ],

        /**
         * @type Model
         */
        model: null,

        /**
         * @type Ui
         */
        ui: null,

        /**
         * @type Config
         */
        config: null,

        /**
         * @type {number}
         */
        lastViewedCaller: 0,

        /**
         * @type {string}
         */
        emulator_msg: 'Application works only on Target. ' +
            'Please run this on Target.',

        /**
         * Return true if device is supported for running application,
         * false otherwise.
         * @return {boolean}
         */
        isDeviceSupported: function isDeviceSupported() {
            return window.navigator.platform.indexOf('i686') === -1;
        },

        /**
         * Initialization function
         */
        init: function App_init() {
            if (!this.isDeviceSupported()) {
                window.alert(this.emulator_msg);
                this.exit();
            }

            // instantiate the libs
            this.config = new Config();
            this.model = new Model();
            this.model.registerChangeListener(this.updateCallLists.bind(this));
            this.ui = new Ui();
            this.updateCallLists();

            return this;
        },

        /**
         * Updates call history and caller detailed history lists
         */
        updateCallLists: function App_updateCallLists() {
            this.ui.updateCheckboxes();
            // workaround - time zone update
            tizen.time.getCurrentDateTime().toLocalTimezone();
            // workaround;
            setTimeout(this.showHistoryForCaller(this.lastViewedCaller), 500);
            this.showCallHistory();
        },

        /**
         * Renders call history view
         */
        showCallHistory: function App_showCallHistory() {
            this.model.getCallHistory(this.ui.showCallHistory.bind(this.ui));
        },

        /**
         * Renders history for caller view
         * @param {string} phoneNumber
         */
        showHistoryForCaller: function App_showHistoryForCaller(phoneNumber) {
            this.lastViewedCaller = phoneNumber;
            this.model.getCallHistoryForCaller(
                phoneNumber,
                this.ui.showHistoryForCaller.bind(this.ui, phoneNumber)
            );
        },

        /**
         * @param {number} personId
         * @returns {string} photoURI Photo URI for specified contact
         */
        getPhotoURIForContact: function App_getPhotoURIForContact(personId) {
            return this.model.getPhotoURIForContact(personId);
        },

        /**
         * Launch extension call service
         * @param {string} phoneNumber
         */
        makeCall: function App_makeCall(phoneNumber) {
            var self = this,
                appControl = new tizen.ApplicationControl(
                    'http://tizen.org/appcontrol/operation/call',
                    'tel:' + phoneNumber
                );
            tizen.application.launchAppControl(
                appControl,
                null,
                function onCallSuccess() {
                    setTimeout(
                        function unlockButtons() {
                            self.ui.unlockButtons();
                        },
                        1500
                    );
                },
                function onCallError(e) {
                    console.error('Call to ' + phoneNumber +
                        ' failed. Call service is unavailable.', e);
                    self.ui.showErrorPopup('Call failed. ' +
                        'Call service is unavailable.');
                    self.ui.unlockButtons();
                },
                {
                    onsuccess: function onCallSuccess() {
                        self.ui.unlockButtons();
                    },
                    onfailure: function onCallError(e) {
                        console.log('App_makeCall: Call to ' + phoneNumber +
                            ' failed. Call service was busy.', e);
                        self.ui.unlockButtons();
                    }
                }
            );
        },

        /**
         * Launch extension sms service
         * @param {string} phoneNumber
         */
        sendSms: function App_sendSms(phoneNumber) {

            var self = this,
                appControl = new tizen.ApplicationControl(
                    'http://tizen.org/appcontrol/operation/compose',
                    'sms:' + phoneNumber
                );

            tizen.application.launchAppControl(
                appControl,
                null,
                null,
                function onSendMessageError(e) {
                    console.error('Message launch error: ', e);
                    self.ui.showErrorPopup('Message service is unavailable');
                    app.ui.unlockOptionButtons();
                },
                {
                    onfailure: function onSendMessageError(er) {
                        console.error('Message service launch error: ', er);
                        self.ui.showErrorPopup(
                            'Message service is unavailable'
                        );
                        app.ui.unlockOptionButtons();
                    }
                }
            );
        },

        /**
         * Deletes specified log entry
         * @param {CallHistoryEntry} entry
         */
        deleteLog: function App_deleteLogs(entry) {
            this.model.deleteLog(entry);
        },

        /**
         * App exit
         */
        exit: function App_exit(event) {
            if (event instanceof Event) {
                event.preventDefault();
                event.stopPropagation();
            }
            tizen.application.getCurrentApplication().exit();
        }
    };
}());
