class Utils

  RECORDING_SRC_PREFIX = 'rec_'
  RECORDING_SOURCES = ["#{RECORDING_SRC_PREFIX}youtube", "#{RECORDING_SRC_PREFIX}soundcloud"]
  USERNAME_SITES = %W{youtube facebook soundcloud bandcamp fandalism twitter reverbnation}
  SITE_TYPES = ['url'].concat(USERNAME_SITES).concat(RECORDING_SOURCES)

  USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.1 Safari/537.36"


  def self.recording_source?(site)
    RECORDING_SOURCES.include?(site)
  end

  def self.extract_recording_data(site, recording_url)
    recording_url.strip!
    rec_data = {}
    case site
    when 'rec_youtube'
      #  regex derived from:  https://gist.github.com/afeld/1254889
      watch = (recording_url =~ /(youtu.be\/|youtube.com\/(watch\?(.*&)?v=|(embed|v)\/))([^\?&\"\'>]+)/)
      rec_data["id"] = $5 if watch

      uri = URI.parse("https://www.googleapis.com/youtube/v3/videos?part=snippet&id=#{$5}&key=#{APP_CONFIG.google_public_server_key}")

      http = Net::HTTP.new(uri.host, uri.port)
      http.use_ssl = true if uri.scheme == 'https'
      req = Net::HTTP::Get.new(uri)
      response = http.request(req)
      if response && response.body.length > 2
        json = response.body.force_encoding("UTF-8")#  .encode('UTF-8', :invalid => :replace, :replace => '')
        json_hash = JSON.parse(json)

        if watch && json_hash["items"] && json_hash["items"].length == 1
          rec_data["title"] = json_hash["items"][0]["snippet"]["title"]
        end
      end

    when 'rec_soundcloud'
      if recording_url =~ /^https?:\/\/.*soundcloud.com\/.+/
        tmpfile = Tempfile.new(site)
        tmpfile.close
        curl_args = "-A  '#{USER_AGENT}' -L --output #{tmpfile.path} --fail --show-error "
        `curl #{curl_args} '#{recording_url}' 2>&1`
        result = File.read(tmpfile.path)
        File.delete(tmpfile.path)
        if result =~ /"soundcloud:\/\/sounds:(\d+)"/
          rec_data["id"] = $1 
        end

        if result =~ /property=\"og:title\" content=\"([\w\W]+)\"><meta property=\"og:image\"/
          rec_data["title"] = $1
        end        
      end
    end
    rec_data.empty? ? nil : rec_data    
  end

  def self.username_url(username, site)
    case site
    when 'youtube'
      "https://www.youtube.com/c/#{username}"
    when 'facebook'
      "https://www.facebook.com/#{username}"
    when 'soundcloud'
      "https://soundcloud.com/#{username}"
    when 'bandcamp'
      "http://#{username}.bandcamp.com"
    when 'bandcamp-fan'
      "http://bandcamp.com/#{username}"
    when 'fandalism'
      "http://fandalism.com/#{username}"
    when 'twitter'
      "https://twitter.com/#{username}"
    when 'reverbnation'
      "http://www.reverbnation.com/#{username}"
    else
      nil
    end
  end

  def self.site_validator(url, site=nil)
    curl_args = "-A '#{USER_AGENT}' --insecure --silent --head --fail --show-error "
    case site
    when 'bandcamp'
      cmd = "curl #{curl_args} '#{url}' 2>&1"
      result = `#{cmd}`.chomp
      if $?.success?
        if /^HTTP\/\d+\.\d+ 2\d\d OK/ =~ result.lines[0]
          return nil
        else
          if /http:\/\/(.*)\.bandcamp.com/ =~ url
            return self.site_validator(self.username_url($1, 'bandcamp-fan'), 'bandcamp-fan')
          end
          return "Unrecognized url (#{url})"
        end
      else
        result =~ /curl: \(\d+\) (.*)/
        return "#{$1} (#{url})"
      end
    else
      curl_args << "-L --output /dev/null "
      cmd = "curl #{curl_args} '#{url}' 2>&1"
      result = `#{cmd}`.chomp
    end
    if $?.success?
      return nil
    else
      result =~ /curl: \(\d+\) (.*)/
      return "#{$1} (#{url})"
    end
  end

end
