module JamRuby
  class ArtifactUpdate < ActiveRecord::Base

    DEFAULT_ENVIRONMENT = 'public'
    CLIENT_PREFIX = 'JamClient'

    PRODUCTS = ["#{CLIENT_PREFIX}/Win32", "#{CLIENT_PREFIX}/MacOSX", "#{CLIENT_PREFIX}/JamBlaster", "#{CLIENT_PREFIX}/JamBlasterClient"]

    self.primary_key = 'id'
    attr_accessible :version, :uri, :sha1, :environment, :product, as: :admin

    mount_uploader :uri, ArtifactUploader

    validates :version, :presence => true
    validates :uri, :presence => true
    validates :sha1, :presence => true
    validates :size, :presence => true
    validates :environment, :presence => true
    validates :product, :inclusion => {:in => PRODUCTS}

    before_validation do
      if uri.present? && uri_changed?
        self.size = uri.file.size
        self.sha1 = Digest::MD5.hexdigest(File.read(uri.current_path))
      end
    end

    def update_data
      {product: product, version: version, uri: determine_url, size: size}
    end

    # called when the client is upgraded (sent to all native clients)
    def send_notice
      Notification.send_client_update(product, version, determine_url, size)
    end

    def self.find_client_by_os(os, environment=DEFAULT_ENVIRONMENT)
      ArtifactUpdate.find_by_product_and_environment("#{CLIENT_PREFIX}/#{os}", environment)
    end

    def determine_url

      if APP_CONFIG.storage_type == :file
        # this is basically a dev-time only path of code; we store real artifacts in s3
        url = APP_CONFIG.jam_admin_root_url + self.uri.url
      else
        url = "https://#{APP_CONFIG.cloudfront_host}/#{self.uri.store_dir}/#{self[:uri]}"
        #url = self.uri.url.gsub(APP_CONFIG.aws_fullhost, APP_CONFIG.cloudfront_host)
      end

      url
    end
  end
end
