# encoding: UTF-8
# El tiempo en Ruby para Subtle
# Nota: wttr.in admite varios idiomas "?lang=idioma"
require 'net/http'
#require 'cgi'

configure :miweather do |s|
  s.interval      = s.config[:interval] || 1800
  s.placeone      = s.config[:placeone] || 'Valencia'
  s.placetwo      = s.config[:placetwo] || ''
  s.placethree    = s.config[:placethree] || ''
  s.placefour     = s.config[:placefour] || ''
  s.placefive     = s.config[:placefive] || ''
  s.separator     = s.config[:separator] || '|'
  s.lang          = s.config[:lang] || 'en'
  s.unit          = s.config[:unit] || 'm'
  s.wind          = s.config[:wind] || 'yes'
  s.xbmicon       = s.config[:xbmicon] || 'yes'
  s.iconsol       = Subtlext::Icon.new('sol2.xbm')
  s.iconnube      = Subtlext::Icon.new('nube.xbm')
  s.iconnubesol   = Subtlext::Icon.new('nubesol.xbm')
  s.iconlluvia    = Subtlext::Icon.new('lluvia.xbm')
  s.iconlluviasol = Subtlext::Icon.new('lluviasol.xbm')
  s.iconniebla    = Subtlext::Icon.new('niebla.xbm')
  s.icontormenta  = Subtlext::Icon.new('tormenta.xbm')
  s.iconnieve     = Subtlext::Icon.new('nieve.xbm')
  s.iconnada      = Subtlext::Icon.new('nada.xbm')
end

helper do
  def elegiricono(texto)
    # Elegir que icono mostrar a partir de un carácter Unicode
    simbolo = iconnada
    corriconos = {"\u2600" => iconsol, \
	"\u26c5" => iconnubesol, \
	"\u{01f32b}" => iconniebla, \
	"\u2601" => iconnube, \
	"\u{01f326}" => iconlluviasol, \
	"\u{01f327}" => iconlluvia, \
	"\u26c8" => icontormenta, \
	"\u{01f329}" => icontormenta, \
	"\u{01f328}" => iconnieve, \
	"\u2744" => iconnieve}
    corriconos.each { |i,j|
      if texto.include?(i) == true
        simbolo = j
        texto = texto.gsub!(" #{i}", "")
      end
    }
    return simbolo
  end

  def refresh_data
    if wind == "no" or wind == ""
      formato = "%l:+%C+%c+%t"
    else
      formato = "%l:+%C+%c+%t,+%w"
    end
    lugares = [placeone, placetwo, placethree, placefour, placefive]
    resultados = []

    lugares.each { |sitio|
      if sitio != ""
        uri = URI("http://wttr.in/#{URI.escape(sitio)}" \
		"?format=#{formato}&lang=#{lang}&#{unit}")
        http = Net::HTTP.new(uri.host, 80)
        http.read_timeout = 500
        request = Net::HTTP::Get.new(uri.request_uri)
        textobasico = http.request(request).body.chomp
        # En el caso de "Guadalajara+Mexico", para esconder "+Mexico":
        sitiodef = sitio.force_encoding('UTF-8').gsub(/\+.*/, "")
        # \ufe0f, un selector de variantes de emojis innecesario aquí:
        textdef = textobasico.force_encoding('UTF-8').gsub("\ufe0f","").gsub(sitio,sitiodef)
        if xbmicon != "no" and xbmicon != ""
          icono = elegiricono(textdef)
          resultados << icono + " " + textdef
        else
          resultados << textdef
        end
      end
    }
      
    self.data = resultados.join(" #{separator} ")
  rescue Exception => excp
    self.data = excp.message
  end
end

on :run do |s|
  refresh_data
end
