require 'httparty'
require 'nokogiri'

def fetch_file_list
  @file_list = {}

  fetch_kind(:file)
  fetch_kind(:template)

end

def fetch_kind(kind, page = 1)

  doc = Nokogiri::XML(HTTParty.get("#{@base_url}/#{kind.to_s}s.xml", query: {per_page: 100, page: page, provider_key: @provider_key}).body)
  doc.xpath("#{kind.to_s}s/*").each do |node|
    cache_id_of(node, kind)
  end

  total_pages_xpath = doc.xpath("//*[@total_pages]")[0]
  total_pages = total_pages_xpath ? total_pages_xpath.attr('total_pages').to_i : 1

  if page < total_pages
    fetch_kind(kind, page + 1)
  end
end

def cache_id_of(node, kind)
  key = node.xpath('path').text
  if key.empty?
    key = node.xpath('system_name').text
  end
  @file_list[key] = {id: node.xpath('id').text, kind: kind}
end

def upload_files(files)
  files.each do |file|
    if File.file?(file)
      system_name = file.gsub('.html.liquid', '')
      key = @file_list["/#{file}"] || @file_list[system_name]
      if key
        p "uploading #{file}"
        case key[:kind]
        when :template
          HTTParty.put("#{@base_url}/templates/#{key[:id]}.xml", body: {provider_key: @provider_key, draft: File.read(file)})
        when :file
          HTTParty.put("#{@base_url}/files/#{key[:id]}.xml", body: {provider_key: @provider_key, attachment: File.new(file)})
        end
      end
    end
  end
end

@provider_key = "vodafone-eca04af29ba68e71eb87294e9fa1e08f"
@base_url = "http://vodafone-admin.3scale.net.dev:3000/admin/api/cms"


fetch_file_list

guard :shell do
  watch(/.*/){|files| upload_files(files)}
end
