<style>
.workbench {
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 14px;
}

h1 {
  color: #ec574d;
  font-size: 16px;
}

a {
  color: #ec574d;
}

.resize-corner {
  position: absolute !important;
  right: -30px;
  bottom: -30px;
  width: 30px;
  height: 30px;
  background: rgba(0,0,0,0.5);
  cursor: hand;
  cursor: -webkit-grab;
  cursor: grab;
  user-select: none;
}

.dragging .resize-corner {
  cursor: move;
}

.dragging {
  -webkit-touch-callout: none;
    -webkit-user-select: none;
     -khtml-user-select: none;
       -moz-user-select: none;
        -ms-user-select: none;
            user-select: none;
  cursor: move;
}

.dragging iframe {
  pointer-events: none;
}

.full-editor {
  min-height: 600px;
}

.workbench-controls {
  list-style: none;
  margin: 40px auto;
  width: 200px;
  padding: 20px;
  background: #fff;
  box-shadow: 0 1px 2px 0 rgba(0,0,0,0.1),0 0 3px 0 rgba(0,0,0,0.1);
}

.workbench-controls li {
  margin: 5px 0;
}

.workbench-controls input {
  border: none;
}

.workbench-controls_control--disabled {
  text-decoration: line-through;
}

.workbench-area {
  position: relative;
  margin: 25px;
  text-align: left;
}

.widget-area {
  vertical-align: top;
  display: inline-block;
  position: relative;
}

.widget-area iframe {
  vertical-align: top;
}

.editor-area {
  position: absolute;
  top: 0;
  right: 0;
}

input {
  color: #ec574d;
}

input[type="number"] {
  float: right;
}


textarea {
  position: absolute;
  top: 0;
  left: 0;
  width: 0;
  height: 0;
  opacity: 0;
}
</style>

<div class="workbench {{ dragging ? 'dragging' : '' }}">
  <ul class="workbench-controls">
    <h1>{{ widget.name }}</h1>
    <li><a href="#" on:click="resetWorkbench()">Reset Workbench</a></li>
    <li><textarea ref:presetOutput bind:value="preset"></textarea><a href="#" on:click="copyPreset(event)">Copy Preset</a></li>
    {{#if compositions && compositions.length}}
    <li>
      <label>Load Composition
        <select bind:value="loadedComposition">
          <option value="new">New</option>
          {{#each compositions as composition}}
          <option value="{{composition.id}}">{{composition.id}}</option>
          {{/each}}
        <select>
      </label>
    </li>
    {{/if}}
    {{#if embedCode}}
    <li><textarea ref:embedCodeOutput bind:value="embedCode"></textarea><a href="#" on:click="copyEmbedCode(event)">Copy Embed Code</a></li>
    {{/if}}
    <li><a href="#" on:click="openStandalone()">Open Standalone Page</a></li>
    <li><label>Width<input type="number" bind:value="width"></label></li>
    <li><label>Height<input type="number" bind:value="height"></label></li>
    <li><label>Autoscale<input type='checkbox' bind:checked='autoscale'/></label></li>
  </ul>
  <div class="workbench-area">
    <div class="editor-area" ref:editorArea></div>
    <div class="widget-area" ref:widgetArea style="width: {{ width }}px; height: {{ height }}px;">
      <div class="resize-corner"
        on:mousedown="set({startWidth: width, startHeight: height})"
        on:drag="set({width: startWidth + event.x, height: startHeight + event.y})"></div>
    </div>
  </div>
</div>

<script>
const copyFrom = textarea => {
  textarea.select();

  try {
    let successful = document.execCommand('copy');
    console.log('Copied!');
  } catch (err) {
    console.log(textarea.value);
    return console.error('Oops, unable to copy', err);
  }
};

export default {
  data() {
    return {
      width: 400,
      height: 400,
      loadedComposition: 'new',
      autoscale: true,
      widget: {
        name: '',
      },
    };
  },

  computed: {
    autoscaleValue: autoscale => (autoscale ? 'on' : 'off'),
    displaySavedComposition: loadedComposition =>
      loadedComposition === 'new' ? false : loadedComposition,
    compositionOptions: (displaySavedComposition, autoscaleValue) =>
      displaySavedComposition
        ? [
            displaySavedComposition,
            { edit_mode: true, autoscale: autoscaleValue },
          ]
        : [{ widget_id: 'widget', edit_mode: true, autoscale: autoscaleValue }],

    embedCode: (displaySavedComposition, height, width, autoscaleValue) =>
      displaySavedComposition &&
      `
      <script>
        window.widgeticOptions = {
          domain: 'local.widgetic.com:8082',
          secure: false,
        }
      </script >
      <script async src="http://local.widgetic.com:8082/modules/@widgetic/sdk/lib/sdk.dev.js"></script >
      <a href="#" class="widgetic-composition" data-autoscale="${autoscaleValue}" data-id="${displaySavedComposition}" data-width="${width}" data-height="${height}" data-brand="bottom-right">
    `,
  },

  events: {
    drag(node, callback) {
      const self = this;
      function onmousedown(event) {
        self.set({ dragging: true });
        const rect = node.getBoundingClientRect();
        const offsetX = event.offsetX;
        const offsetY = event.offsetY;

        function drop() {
          self.set({ dragging: false });
          document.body.removeEventListener('mouseup', drop, false);
          document.body.removeEventListener('mousemove', drag, false);
        }

        function drag(event) {
          const x =
            event.pageX - (offsetX + rect.left + document.body.scrollLeft);
          const y =
            event.pageY - (offsetY + rect.top + document.body.scrollTop);
          callback({ x, y });
        }

        document.body.addEventListener('mouseup', drop, false);
        document.body.addEventListener('mousemove', drag, false);
      }

      node.addEventListener('mousedown', onmousedown, false);

      return {
        teardown() {
          node.removeEventListener('mousedown', onmousedown, false);
        },
      };
    },
  },

  oncreate() {
    // init Widgetic SDK
    Widgetic.init('bogus', 'bogus');
    Widgetic.auth.token('bogus');

    // persist settings across reloads
    try {
      this.set(JSON.parse(localStorage.wkbncSettings));
    } catch (e) {}

    const persistSettings = _ => {
      const { width, height, autoscale, widget } = this.get();
      localStorage.wkbncSettings = JSON.stringify({
        width,
        height,
        autoscale,
        widget,
      });
    };
    window.addEventListener('unload', persistSettings);
    this.disposeUnload = _ =>
      window.removeEventListener('unload', persistSettings);

    // display the widget
    this.observe('compositionOptions', compositionOptions => {
      const composition = this.get('composition');
      composition && composition.close();
      this.set({
        composition: Widgetic.UI.composition(
          this.refs.widgetArea,
          compositionOptions[0],
          compositionOptions[1]
        ),
      });
    });

    // create the editor
    this.observe('composition', composition => {
      let editor = this.get('editor');
      editor && editor.close();
      editor = Widgetic.UI.editor(this.refs.editorArea, composition);
      this.set({ editor });
      return editor.on('composition:save', savedComposition => {
        this.refreshCompositions();
      });
    });

    Widgetic.api('widgets/widget').then(data => this.set({ widget: data }));
    this.refreshCompositions();
  },

  methods: {
    refreshCompositions() {
      Widgetic.api('compositions').then(data =>
        this.set({ compositions: data })
      );
    },

    copyEmbedCode(event) {
      event.preventDefault();
      copyFrom(this.refs.embedCodeOutput);
    },

    copyPreset(event) {
      event.preventDefault();

      let preset = JSON.parse(
        JSON.stringify(
          this.get('editor')
            ._iframe.contentWindow.require('core/models/composition')
            .first()
            .getSkin()
        )
      );
      delete preset.uses;
      delete preset.metas;
      delete preset.widget_id;
      delete preset.user_id;

      this.set({
        preset: JSON.stringify(
          Object.assign({ id: preset.id }, preset),
          null,
          '\t'
        ),
      });

      copyFrom(this.refs.presetOutput);
    },

    resetWorkbench() {
      this.disposeUnload();
      localStorage.clear();
      window.location.reload();
    },

    openStandalone() {
      window.open(this.get('composition')._iframe.src);
    },
  },
};
</script>
