(function (context, $) {

  "use strict";

  context.JK = context.JK || {};
    context.JK.SampleRate = function (app) {

    var $sampleRate = null;
    var $self = $(this);
    var logger = context.JK.logger;
    var lastSelectedDevice = null;

    var SAMPLERATE_CHANGED = 'sample_rate.sample_rate_changed';

    var BACKEND_SAMPLE_RATES = {
      JAMKAZAM_AUTO_SR: 0,
      USE_DEVICE_DEFAULT_SR: 1,
      PREFER_44: 2,
      PREFER_48: 3,
      PREFER_96: 4,
      PREFER_88: 5
    }

    function setLastSelectedDevice(_lastSelectedDevice) {
      lastSelectedDevice = _lastSelectedDevice;
    }

    function getLastSelectedDevice() {
      return lastSelectedDevice;
    }

    function selectedSampleRate() {

      return BACKEND_SAMPLE_RATES[$sampleRate.val()];
    }

    function selectSampleRate(value) {

      var setter = 'PREFER_44'
      if(value == 44100) {
        setter = 'PREFER_44'
      }
      else if(value == 48000) {
        setter = 'PREFER_48'
      }
      else if(value == 96000) {
        setter = 'PREFER_96'
      }
      else if (value == 'DEVICE_DEFAULT') {
        setter = 'USE_DEVICE_DEFAULT_SR'
      }
      console.log("SELECT SAMPLE RATE" + value, setter);
      context.JK.dropdown($sampleRate.val(setter).easyDropDown('select', setter.toString(), true))
    }

    function render() {
      context.JK.dropdown($sampleRate);
    }

    function disable() {
      $sampleRate.attr("disabled", "disabled").easyDropDown('disable');
    }

    function enable() {
      $sampleRate.removeAttr("disabled").easyDropDown('enable');
    }

    function resetValues() {
      $sampleRate.val('USE_DEVICE_DEFAULT_SR').easyDropDown('select', 'USE_DEVICE_DEFAULT_SR', true)

    }

    function events() {
      $sampleRate.unbind('change').change(function () {
        $self.triggerHandler(SAMPLERATE_CHANGED, {value: selectedSampleRate()});
      });
    }

    function initialize(_$sampleRate) {

      $sampleRate = _$sampleRate;
      if(!_$sampleRate.is('.select-sample-rate')) {
        throw "$sampleRate != .select-sample-rate"
      }

      events();
      render();
    }

    this.SAMPLERATE_CHANGED   = SAMPLERATE_CHANGED;
    this.initialize           = initialize;
    this.selectedSampleRate   = selectedSampleRate;
    this.selectSampleRate     = selectSampleRate;
    this.render               = render;
    this.enable               = enable;
    this.disable              = disable;
    this.resetValues          = resetValues;
    this.getLastSelectedDevice = getLastSelectedDevice;
    this.setLastSelectedDevice = setLastSelectedDevice;

    return this;
  }


})(window, jQuery);