ActiveResource::Base.include_root_in_json = false

module ActiveTender
  class Base < ActiveResource::Base
    
    DEFAULT_DOMAIN = "DOMAIN"
    DEFAULT_HOST   = "api.tenderapp.com"
    DEFAULT_SITE   = "https://#{DEFAULT_HOST}/#{DEFAULT_DOMAIN}/"
    DEFAULT_API_KEY = "API_KEY"
    
    self.site = DEFAULT_SITE
    self.format = :json
    self.headers['X-Tender-Auth'] = DEFAULT_API_KEY
    self.headers['Accept'] = 'application/vnd.tender-v1+json'
        
    class << self
      attr_accessor :domain, :host, :port, :api_key
          
      def configure(&block)
        yield self
      end

      def domain(value)
        self.site = DEFAULT_SITE unless self.site
        self.site = self.site.to_s.gsub(/(.*\/)\w*(\/)$/, '\1' + value + '\2')
      end

      def host(value)
        self.site = DEFAULT_SITE unless self.site
        self.site = self.site.to_s.gsub(/^(https:\/\/).*(\/\w*\/)$/, '\1' + value + '\2')
      end

      def port(value)
        self.site = DEFAULT_SITE unless self.site
        self.site = self.site.to_s.gsub(/^(https:\/\/.*)(\/\w*\/)$/, '\1' + ":#{value.to_s}" + '\2')
      end

      def api_key(value)
        self.headers['X-Tender-Auth'] = value
      end

      def count
        all.count
      end
      
      ## Remove format from the url.
      def element_path(id, prefix_options = {}, query_options = nil)
        prefix_options, query_options = split_options(prefix_options) if query_options.nil?
        "#{prefix(prefix_options)}#{collection_name}/#{id}#{query_string(query_options)}"
      end

      # Gets the collection path for the REST resources.  If the +query_options+ parameter is omitted, Rails
      # will split from the +prefix_options+.
      #
      # ==== Options
      # * +prefix_options+ - A hash to add a prefix to the request for nested URLs (e.g., <tt>:account_id => 19</tt>
      #   would yield a URL like <tt>/accounts/19/purchases.xml</tt>).
      # * +query_options+ - A hash to add items to the query string for the request.
      #
      # ==== Examples
      #   Post.collection_path
      #   # => /posts.xml
      #
      #   Comment.collection_path(:post_id => 5)
      #   # => /posts/5/comments.xml
      #
      #   Comment.collection_path(:post_id => 5, :active => 1)
      #   # => /posts/5/comments.xml?active=1
      #
      #   Comment.collection_path({:post_id => 5}, {:active => 1})
      #   # => /posts/5/comments.xml?active=1
      #
      def collection_path(prefix_options = {}, query_options = nil)
        prefix_options, query_options = split_options(prefix_options) if query_options.nil?
        "#{prefix(prefix_options)}#{collection_name}#{query_string(query_options)}"
      end

      ## For a collection call, ActiveResource formatting is not 
      ## compliant with ActiveTender's output.
      def instantiate_collection(collection, prefix_options = {})
      if collection['total']
          records = collection[collection_name].collect! { |record| instantiate_record(record, prefix_options) }
          page = collection['offset'] >= 30 ? collection['offset']/30 + 1 : 1
          WillPaginate::Collection.create(page, collection['per_page'], collection['total']) do |pager|
            pager.replace records
          end
        else
          [instantiate_record(collection, prefix_options)]
        end
      end

      ##  Following method from ActiveResource::CustomMethods extends the capabilities of activeresource for non-standard urls ;-)
      ##  The objects returned from this method are not automatically converted into ActiveResource instances - they are ordinary Hashes. 
      ##  Modifications below ensures that you get ActiveResource instances.
      def get(options = {})
        url = custom_method_collection_url(options)
        result = connection.get(url, headers)
        if result.class.is_a? WillPaginate::Collection
          result.collect! {|record| self.class.new.load(record)}
        else
          self.class.new.load(result)
        end
      end

      # If headers are not defined in a given subclass, then obtain
      # headers from the superclass.
      def headers
        if defined?(@headers)
          @headers
        elsif superclass != Object && superclass.headers
          superclass.headers
        else
          @headers ||= {}
        end
      end
      
            
    end
                        
    # Instance Methods: (modifying the ActiveRecord::CustomMethods).
    # def id
    #   href.gsub(/.*\//, '').to_i if self.respond_to? :href
    # end

    def headers
      Base.headers
    end

    ## This modification is same as defined in above method 
    def get(options = {})
      self.class.new.load(connection.get(custom_method_element_url(options), self.class.headers))
    end

    ## Modifying the url formation to make it ActiveTender API complaint
    def custom_method_element_url(options = {})    
      "#{self.class.prefix(prefix_options)}#{self.class.collection_name}/#{id}#{self.class.send!(:query_string, options)}"
    end

  end

end