#!/usr/bin/env ruby
# Encoding: utf-8

require "fileutils"
require "http"
require "nokogiri"
require "zlib"
require "stringio"                  

class Csfd

  ENDPOINT = 'https://www.csfd.cz' 
  
  def initialize
    @httpClient = HTTP.persistent(Csfd::ENDPOINT).follow
  end

  def getId(movie)
    path = '/hledat/?q=' + URI.encode(movie.encode('utf-8'))
    link = getElement(path, "//div[@id='search-films']//h3[@class='subject']//a")    
    return link.first ? link.first["href"].gsub(/^\/film\/([0-9]+)-.*?$/, '\1') : nil
  end

  def getRating(id)
    path = '/film/' + id
    meta = getElement(path, "//meta[@itemprop='ratingValue']")
    return meta.first["content"]    
  end

  def getLength(id)
    path = '/film/' + id + '/prehled/'
    info = getElement(path, "//p[@class='origin']")
    return info.first.content.split(', ')[2].to_i
  end
  
  def getElement(path, xpath)
    begin
      ctx = OpenSSL::SSL::SSLContext.new
      ctx.verify_mode = OpenSSL::SSL::VERIFY_NONE

      response = @httpClient.get(Csfd::ENDPOINT + path, :ssl_context => ctx)
    rescue HTTP::Error => e
      puts "Chyba site" + e.message
      exit
    end
    
    if response.headers["content-encoding"] == 'gzip'
        body = gzdecode(response.to_s)
    else
        body = response.to_s       
    end
    
    html = Nokogiri::HTML(body)
    return html.xpath(xpath)
  end
  
  def gzdecode(data)
    return Zlib::GzipReader.new(StringIO.new(data)).read 
  end
end

csfd = Csfd.new()
dir = Dir.pwd

print "Hledat filmy v #{dir}? (a/n) " 
input = gets.strip

if input != 'a'
    exit
end

Dir.foreach(dir) do |item|
    path = dir + '/' + item 
    next if item == '.' or item == '..' or File.directory?(path) == false

    if (!item.match(/[0-9]+ min\)$/))
        print item + '...'
        
        id = csfd.getId(item)

        if id
            rating = csfd.getRating(id)
            length = csfd.getLength(id)
            append = " (#{rating} %, #{length} min)" 
            print append + "\n"
            
            FileUtils.mv(path, path + append)
        else
            print " nenalezeno\n" 
        end
    end
end

sleep 1
