/**
 * @version 0.0.1
 * @name tastypie
 * @cat Plugins/Rest
 * @author Nikitin Sergey <nikitinsm@gmail.com>
 */

jQuery.tastypie = {
  
  defaults: {
    server: 'http://api.esmeralda.ru/',
    api: 'public',
    resource: '',
    detail: '',
    data: {
      format: 'jsonp',
    },
    success: function(response){}
  },
  
  options: {},

  init: function(options){
    $.extend(true, this.options, this.defaults, options);
    
    //clean
    this.options.server = this.options.server.replace(/\/$/g, '');
    this.options.api = this.options.api.replace(/\//g, '');
    this.options.resource = this.options.resource.replace(/\//g, '');
    this.options.detail = this.options.detail.replace(/\//g, '');
    
    //validate
    if (this.options.resource == '') {
      throw 'Option \'resource\' must be specified';
    }
  },
  
  finish: function(){
    
  },
  
  read: function(settings){
    this.init(settings);
    this.request('GET');
  },
  
  replace: function(settings){
    this.init(settings);
    this.request('PUT');
  },
  
  create: function(settings){
    this.init(settings);
    this.request('POST');
  },
  
  'delete': function(settings){
    this.init(settings);
    this.request('DELETE');
  },
  
  request: function(method){
    $.ajax({
      url: this.url(),
      type: method,
      dataType: this.options.data.format,
      data: this.options.data,
      success: this.options.success
    });
  },

  url: function(){
    var url = this.options.server + '/' + this.options.api + '/' + this.options.resource + '/'
    if(this.options.detail.length > 5){
      url += this.options.detail + '/'
    }
    return url
  }
};

