(function (paw, utils) {
    function TraceToggleComponent($elt, settings){
        this.$elt = $elt;
        this.settings = paw.lang.append({
            getTraceKeyApi: undefined,
            toggleTraceApi: undefined
        }, settings);

        this.traceKey = null;
        this.$indicator = null;
        this.isToggling = false;
    }

    TraceToggleComponent.prototype.init = function(){
        var self = this;

        this.$indicator = this.$elt.find('.paw-trace-toggle-indicator');

        this.$elt.on('click', function(){
            self.toggleTrace().then(function(){
                self.renderState();
            });
        });

        this.getTraceKey().then(function(){
            self.renderState();
        });
    };

    TraceToggleComponent.prototype.getTraceKey = function(){
        var self = this;
        return utils.async.get(this.settings.getTraceKeyApi).then(function(traceKey){
            self.traceKey = traceKey;
        });
    };

    TraceToggleComponent.prototype.toggleTrace = function(){
        var self = this;
        if(this.isToggling){
            return utils.async.promise();
        }
        self.isToggling = true;
        return utils.async.get(this.settings.toggleTraceApi, {
            cache: false
        }).then(function(traceKey){
            self.traceKey = traceKey;
        }).finally(function(){
            self.isToggling = false;
        });
    };

    TraceToggleComponent.prototype.isActive = function(){
        return utils.value.isSet(this.traceKey) && this.traceKey.length > 0;
    };
    
    TraceToggleComponent.prototype.renderState = function(){
        if(this.isActive()){
            this.$elt.addClass('paw-active');
            return;
        }
        this.$elt.removeClass('paw-active');
    };

    paw.com.trace.TraceToggleComponent = TraceToggleComponent;
})(paw, paw.utils);