import addons from '@storybook/addons';
import Events from '@storybook/core-events';
import KnobManager from './KnobManager';

export const manager = new KnobManager();
const { knobStore } = manager;

function forceReRender() {
  addons.getChannel().emit(Events.FORCE_RE_RENDER);
}

function setPaneKnobs(timestamp = +new Date()) {
  const channel = addons.getChannel();
  channel.emit('addon:knobs:setKnobs', { knobs: knobStore.getAll(), timestamp });
}

function knobChanged(change) {
  const { name, type, value } = change;

  // Update the related knob and it's value.
  const knobOptions = knobStore.get(name);

  if (type === 'boolean') {
    knobOptions.value = !knobOptions.value;
  } else {
    knobOptions.value = value;
  }
  knobStore.markAllUnused();

  forceReRender();
}

function knobClicked(clicked) {
  const knobOptions = knobStore.get(clicked.name);
  knobOptions.callback();
}

function resetKnobs() {
  knobStore.reset();

  forceReRender();

  setPaneKnobs(false);
}

function disconnectCallbacks() {
  const channel = addons.getChannel();
  channel.removeListener('addon:knobs:knobChange', knobChanged);
  channel.removeListener('addon:knobs:knobClick', knobClicked);
  channel.removeListener('addon:knobs:reset', resetKnobs);
  knobStore.unsubscribe(setPaneKnobs);
}

function connectCallbacks() {
  const channel = addons.getChannel();
  channel.on('addon:knobs:knobChange', knobChanged);
  channel.on('addon:knobs:knobClick', knobClicked);
  channel.on('addon:knobs:reset', resetKnobs);
  knobStore.subscribe(setPaneKnobs);

  return disconnectCallbacks;
}

export function registerKnobs() {
  addons.getChannel().emit(Events.REGISTER_SUBSCRIPTION, connectCallbacks);
}

@@ -499,14 +499,8 @@
 ame,
- type,
  val
@@ -514,16 +514,16 @@
 change;%0A
+
 %0A  // Up
@@ -608,93 +608,8 @@
 );%0A%0A
-  if (type === 'boolean') %7B%0A    knobOptions.value = !knobOptions.value;%0A  %7D else %7B%0A  
   kn
@@ -637,12 +637,8 @@
 ue;%0A
-  %7D%0A
   kn

Revert "Fix the output of the boolean knob"