var _ = require('underscore');
var Backbone = require('backbone');
var CustomBaselayerModel = require('builder/data/custom-baselayer-model');

/**
 * Model for an individual WMS/WMTS layer.
 */

module.exports = Backbone.Model.extend({

  defaults: {
    state: 'idle' // idle, saving, saveDone, saveFail
  },

  url: function () {
    return this._wmsService.saveLayerURL({
      title: this.get('title'),
      name: this.get('name'),
      layer: this.get('name'),
      srs: this.get('srs'),
      bounding_boxes: this.get('llbbox'),
      type: this.get('type'), // wms/wmts
      matrix_sets: this.get('matrix_sets')
    });
  },

  sync: function (method, model, options) {
    options = options || {};
    options.url = this.url(method.toLowerCase());
    options.dataType = 'jsonp';
    options.attrs = '_';
    method = 'READ';

    return Backbone.sync.apply(this, arguments);
  },

  initialize: function (attrs, opts) {
    if (!opts.wmsService) throw new Error('wmsService is required');

    this._wmsService = opts.wmsService;
  },

  canSave: function (customBaselayersCollection) {
    return !_.any(customBaselayersCollection.isCustomCategory(), function (customLayer) {
      return customLayer.get('name') === this.get('title');
    }, this);
  },

  createProxiedLayerOrCustomBaselayerModel: function () {
    this.set('state', 'saving');
    this._shouldBeProxied() ? this._createProxiedLayer() : this._newCustomBaselayerModel();
  },

  _shouldBeProxied: function () {
    if (this.get('type') === 'wmts') {
      var supportedMatrixSets = this._wmsService.supportedMatrixSets(this.get('matrix_sets') || []);

      return supportedMatrixSets.length > 0;
    }

    return true;
  },

  _createProxiedLayer: function () {
    var self = this;

    this.save({}, {
      success: function () {
        var proxiedBaselayerModel;

        try {
          proxiedBaselayerModel = self._newProxiedBaselayerModel();
        } catch (e) {
        }

        if (proxiedBaselayerModel) {
          self._setCustomBaselayerModel(proxiedBaselayerModel);
        } else {
          self.set('state', 'saveFail');
        }
      },
      error: function (e) {
        self.set('state', 'saveFail');
      }
    });
  },

  _newCustomBaselayerModel: function () {
    var customBaselayerModel = this._byCustomURL(this._xyzURLTemplate());

    customBaselayerModel.set({
      name: this.get('title') || this.get('name'),
      attribution: this.get('attribution'),
      bounding_boxes: this.get('llbbox')
    });
    this._setCustomBaselayerModel(customBaselayerModel);

    return customBaselayerModel;
  },

  _newProxiedBaselayerModel: function () {
    if (!this.get('mapproxy_id')) {
      throw new Error('mapproxy_id must be set');
    }

    var url = this._wmsService.getProxyTilesURL() + '/' + this.get('mapproxy_id') + '/wmts/map/webmercator/{z}/{x}/{y}.png';
    var proxiedBaselayerModel = this._generateCustomBaselayerModel(url);

    proxiedBaselayerModel.set({
      name: this.get('title') || this.get('name'),
      attribution: this.get('attribution'),
      proxy: true,
      bounding_boxes: this.get('bounding_boxes')
    });

    return proxiedBaselayerModel;
  },

  _generateCustomBaselayerModel: function (url) {
    var layer = new CustomBaselayerModel({
      urlTemplate: url,
      attribution: null,
      maxZoom: 21,
      minZoom: 0,
      name: '',
      category: 'WMS',
      tms: false,
      type: 'Tiled'
    });
    layer.set('className', layer._generateClassName(url));

    return layer;
  },

  _byCustomURL: function (url) {
    // Minimal test for "valid URL" w/o having to complicate it with regex
    if (url && url.indexOf('/') === -1) throw new TypeError('invalid URL');

    // Only lowercase the placeholder variables, since the URL may contain case-sensitive data (e.g. API keys and such)
    url = url.replace(/\{S\}/g, '{s}')
      .replace(/\{X\}/g, '{x}')
      .replace(/\{Y\}/g, '{y}')
      .replace(/\{Z\}/g, '{z}');

    var layer = this._generateCustomBaselayerModel(url);

    return layer;
  },

  _xyzURLTemplate: function () {
    var urlTemplate = this.get('url_template') || '';
    // Convert the proxy template variables to XYZ format, http://foo.com/bar/%%(z)s/%%(x)s/%%(y)s.png"
    return urlTemplate.replace(/%%\((\w)\)s/g, '{$1}');
  },

  _setCustomBaselayerModel: function (customBaselayerModel) {
    this.set({
      state: 'saveDone',
      customBaselayerModel: customBaselayerModel
    });
  }

});

@@ -134,16 +134,51 @@
 model');
+%0Aconst DEFAULT_MATRIX_SET = '3857';
 %0A%0A/**%0A *
@@ -4190,16 +4190,310 @@
  %7C%7C '';%0A
+    const matrixSets = this.get('matrix_sets') %7C%7C %5B%5D;%0A%0A    if (matrixSets.length === 0) %7B%0A      throw new Error('The service does not support any SRS.');%0A    %7D%0A%0A    let matrixSet = DEFAULT_MATRIX_SET;%0A%0A    if (!matrixSets.includes(DEFAULT_MATRIX_SET)) %7B%0A      matrixSet = matrixSets%5B0%5D;%0A    %7D%0A%0A
     // C
@@ -4541,17 +4541,24 @@
 Z format
-,
+:%0A    //
  http://
@@ -4570,16 +4570,36 @@
 om/bar/%25
+(tile_matrix_set)s/%25
 %25(z)s/%25%25
@@ -4619,22 +4619,29 @@
 ng%22%0A    
-return
+urlTemplate =
  urlTemp
@@ -4678,16 +4678,117 @@
 %7B$1%7D');%0A
+    urlTemplate = urlTemplate.replace(/%25%5C(tile_matrix_set%5C)s/g, matrixSet);%0A%0A    return urlTemplate;%0A
   %7D,%0A%0A  

Replace the var `tile_matrix_set` from the WMS Proxy