#!/usr/bin/env ruby

require File.expand_path(File.join(File.dirname(__FILE__), '..', 'config', 'environment'))

sensor = Sensor.root
sensors_json = sensor.children_json.to_json
sensor_ids = sensor.all_children_ids(true)

# Create structure
dir = "/tmp/#{Time.now.to_i}"
Dir.mkdir dir

FileUtils.mkdir_p "#{dir}/images"
FileUtils.mkdir_p "#{dir}/images/rotated"
FileUtils.mkdir_p "#{dir}/otherCsv"
FileUtils.mkdir_p "#{dir}/jsonFiles"

File.open("#{dir}/jsonFiles/sensors.json", 'w') do |f|
  f.write(sensors_json)
end

# Create maps.json
maps_json = {}

OverlayMap.where(sensor_id: sensor_ids)
  .where.not(original_image_file_name: nil).each do |overlay_map|
    maps_json[overlay_map.sensor_id] = overlay_map.as_json

    # Include GPS Points
    maps_json[overlay_map.sensor_id].merge!(
      gps_markers: overlay_map.gps_markers.as_json
    )

    begin
      # Download original image
      Redborder::RulesUpdate.download_file(
        overlay_map.original_image_uri.to_s,
        "#{dir}/images/#{overlay_map.sensor_id}"
      )

      # Download rotated image
      Redborder::RulesUpdate.download_file(
        overlay_map.image_uri.to_s,
        "#{dir}/images/rotated/#{overlay_map.sensor_id}"
      )
    rescue OpenURI::HTTPError => e
      Rails.logger.error "Missing image #{overlay_map.image_uri.to_s} during export sensor tree"
    end
  end

File.open("#{dir}/jsonFiles/maps.json", 'w') do |f|
  f.write(maps_json.to_json)
end

# Compress directory
tar_file = "#{Rails.root}/tmp/Export_sensor_tree_#{Time.now.to_i}_#{Random.rand(1000)}.tar.gz"
system('tar', 'cvzf', tar_file, '-C', dir, 'images', 'otherCsv', 'jsonFiles')

puts "Exported at: #{tar_file}"
