class Extension
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Slug
  include Mongoid::Elasticsearch

  include CategoryFilter

  field :title, type: String
  field :author, type: String
  field :extension, type: String
  field :description, type: String
  field :category_id, type: String
  field :repository, type: String
  field :git_url, type: String
  field :key, type: String
  field :version, type: String
  field :price, type: Float
  field :tag, type: String

  slug :title, history: true

  has_many :previews, class_name: 'Preview'
  accepts_nested_attributes_for :previews, :allow_destroy => true

  belongs_to :category

  mount_uploader :extension, ProductUploader
  mount_uploader :thumbnail, ImageUploader

  
  elasticsearch!

  # after_save :get_version_number

  SORT_TYPE = %w{Popular New Preferred}

  def get_version_number
    url = "#{self.repository}/raw/master/lib/#{self.key}/version.rb"
    response = Net::HTTP.get_response(URI.parse(url)).body
    data = HTTParty::Parser.new(response, 'rb').parse
    version = data.gsub!(/\s+/, "").tr!('"','').gsub("module#{self.key.capitalize}VERSION=",'').gsub("end",'')
    self.update(version: version)
  end

  def self.get_categories
    categories = Category.where(type: "Extension")
  end
end
