/* globals define */
define(['jquery', './mustache.min', 'text!./render.html', 'css!./design.css'], function($, Mustache, template, css) {
  'use strict';
  // ----------------------------------------------
  // Create a Mustache-based component implemention
  // ----------------------------------------------
  var SampleComponentImpl = function(args) {
    this.SitesSDK = args.SitesSDK;
    // Initialze the custom component
    this.createTemplate(args);
    this.setupCallbacks();
  };
  // create the template based on the initial values
  SampleComponentImpl.prototype.createTemplate = function(args) {
    // create a unique ID for the div to add, this will be passed to the callback
    this.contentId = args.id + '_content_' + args.viewMode;
    // create a hidden custom component template that can be added to the DOM 
    this.template = '<div id="' + this.contentid + '">' +
      template +
      '</div>';
  };
  SampleComponentImpl.prototype.updateSettings = function(settings) {
    if (settings.property === 'customSettingsData') {
        this.update(settings.value);
    }
  };
  SampleComponentImpl.prototype.update = function(data) {
    this.data = data;
    this.container.html(Mustache.to_html(this.template, this.data));
  };
  //
  // SDK Callbacks
  // setup the callbacks expected by the SDK API
  //
  SampleComponentImpl.prototype.setupCallbacks = function() {
    //
    // callback - render: add the component into the page
    //
    this.render = $.proxy(function(container) {
       this.container = $(container);
       this.SitesSDK.getProperty('customSettingsData', $.proxy(this.update, this));
    }, this);
    //
    // callback - SETTINGS_UPDATED: retrive new custom data and re-render the component
    //
    this.SitesSDK.subscribe(this.SitesSDK.MESSAGE_TYPES.SETTINGS_UPDATED, $.proxy(this.updateSettings, this));
    //
    // callback - dispose: cleanup after component when it is removed from the page
    //
    this.dispose = $.proxy(function() {
       // nothing required
    }, this);
  };
  // ----------------------------------------------
  // Create the factory object for your component
  // ----------------------------------------------
  var sampleComponentFactory = {
    createComponent: function(args, callback) {
      // return a new instance of the component
      return callback(new SampleComponentImpl(args));
    }
  };
  return sampleComponentFactory;
});