/*
 * 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, console, window, navigator*/
/*jslint plusplus: true*/

/**
 * Month module
 */

define({
    name: 'models/stream',
    requires: [
        'core/event'
    ],
    def: function modelsStream(e) {
        'use strict';

        var INIT_MAX_ATTEMPTS = 3,
            INIT_ATTEMPT_TIMEOUT = 500,

            initAttemtps = 0;

        /**
         * Gets media stream.
         */
        function getUserMedia(onUserMediaSuccess, onUserMediaError) {
            navigator.webkitGetUserMedia(
                {
                    video: false,
                    audio: true
                },
                onUserMediaSuccess,
                onUserMediaError
            );
        }

        /**
         * Fires models.stream.ready event onGetUserMediaSuccess.
         * @param {LocalMediaStream} stream
         */
        function onUserMediaSuccess(stream) {
            initAttemtps = 0;
            e.fire('ready', {stream: stream});
        }

        /**
         * Fires models.stream.cannot.access.audio event on onGetUserMediaError.
         */
        function onUserMediaError() {
            initAttemtps += 1;
            if (initAttemtps >= INIT_MAX_ATTEMPTS) {
                initAttemtps = 0;
                e.fire('cannot.access.audio');
                return;
            }
            // Application tries to obtain audio stream up to 3 times
            // because other application may not release it yet
            window.setTimeout(
                function retry() {
                    getUserMedia(onUserMediaSuccess, onUserMediaError);
                },
                INIT_ATTEMPT_TIMEOUT
            );
        }

        function getStream() {
            return getUserMedia(onUserMediaSuccess, onUserMediaError);
        }

        return {
            getStream: getStream
        };
    }

});
