/* global jQuery, wp */

(function ($) {
  'use strict';

  function openFrame(title, buttonText, onSelect) {
    if (!wp || !wp.media || typeof wp.media !== 'function') {
      return;
    }

    var frame = wp.media({
      title: title || 'Select image',
      button: { text: buttonText || 'Use this image' },
      multiple: false,
      library: { type: 'image' }
    });

    frame.on('select', function () {
      var attachment = frame.state().get('selection').first();
      if (!attachment) {
        return;
      }

      var json = attachment.toJSON ? attachment.toJSON() : null;
      var url = json && json.url ? String(json.url) : '';

      if (url && typeof onSelect === 'function') {
        onSelect(url, json);
      }
    });

    frame.open();
  }

  function updatePreview($wrap, url) {
    var $img = $wrap.find('img.wpsn-media-preview').first();
    if (!$img.length) {
      return;
    }

    if (url) {
      $img.attr('src', url);
      $img.show();
      return;
    }

    $img.attr('src', '');
    $img.hide();
  }

  function initField($wrap) {
    if (!$wrap || !$wrap.length) {
      return;
    }

    var $input = $wrap.find('.wpsn-media-url').first();
    if (!$input.length) {
      return;
    }

    // Initial state.
    updatePreview($wrap, $input.val());

    $wrap.on('click', '.wpsn-media-select', function (e) {
      e.preventDefault();
      var $btn = $(this);
      var title = $btn.data('title') || 'Select image';
      var buttonText = $btn.data('button') || 'Use this image';

      openFrame(title, buttonText, function (url) {
        $input.val(url).trigger('change');
        updatePreview($wrap, url);
      });
    });

    $wrap.on('click', '.wpsn-media-clear', function (e) {
      e.preventDefault();
      $input.val('').trigger('change');
      updatePreview($wrap, '');
    });
  }

  $(function () {
    $('.wpsn-media-field').each(function () {
      initField($(this));
    });
  });
})(jQuery);
