#encoding: utf-8

require 'net/http'
require 'net/https'

class XmlController < ApplicationController
  before_action :login_required
  layout "application"

  include ApplicationHelper

  def index
    
  end
  
  def export
    unless theUser(session).can_export_any?
      flash[:notice] = "Sie haben keine Exportberechtigungen"
      redirect_to :controller => :start
    end
    federal_states_query = case
      when theUser(session).can_export_global? then
        ActiveRecord::Base.connection.execute("SELECT fs.federal_key, fs.name \n"+
          "FROM l_federal_state fs \n"+
          "WHERE fs.id < 17 \n"+
          "ORDER BY fs.id")
      else 
        ActiveRecord::Base.execute_sql("SELECT fs.federal_key, fs.name \n"+
          "FROM l_federal_state fs \n"+
          "JOIN model.federal_states_users fu ON user_id = ? AND fu.federal_state_id = fs.id \n"+
          "ORDER BY fs.id",session[:user])
      end
    @federal_states = federal_states_query.to_a.collect { |e| [e['name'],e['federal_key']]  }
    @reporting_periods = ActiveRecord::Base.connection.execute("SELECT key_report FROM reporting_periods ORDER BY key_report").to_a.collect { |e| [e['key_report']]  }
  end
  
  def download  
    #XML_API_URI sollte am Ende von config/environment.rb definiert werden, und ohne trailing slash angegeben werden, z.B. XML_API_URI = "http://localhost:3000"
    #Diese Datei ist im svn ignoriert, also muss die Konstante bei jedem Deployment neu gesetzt werden
    uri = URI.parse(XML_API_URI) 
    init_header = {'user' => theUser(session).loginname, 'Accept' => '*/*'}
    if params[:existdb] == 'existdb'
      init_header['scramble'] = 'true'
    end
    http = Net::HTTP.new(uri.host,uri.port)
    if uri.scheme == "https"
       http.use_ssl = true
       http.verify_mode = OpenSSL::SSL::VERIFY_NONE
    end 
    http.start
    #puts "Requesting #{"#{uri.path}/export/#{params[:jahr]}/#{params[:bl]}"}"
    #puts "params is nämlich #{params.to_s}"
    req_download = http.request_get("#{uri.path}/export/omittive/#{params[:jahr]}/#{params[:bl]}",init_header)
    http.finish
    #puts "####{req_download.code} vs #{Net::HTTPSuccess}"
    case req_download
      when Net::HTTPSuccess
         if params[:existdb] == 'existdb'
           @result = req_download.body
           @result.gsub!(/\n/, "<br />\n");
           # @result.encode!('UTF-8', :invalid => :replace, :undef => :replace)
           render
         else
           send_data(req_download.body, :filename => "ekommu_export_#{params[:bl]}_#{params[:jahr]}_#{Time.now.strftime("%Y-%m-%d_%H%M%S")}.xml", :type => "application/xml")
         end
      else
         @result = req_download.body
         # @result.encode!('UTF-8', :invalid => :replace, :undef => :replace)
         render # :text => req_download.body#.force_encoding("utf-8")
    end
  end
  
  def import
    unless theUser(session).can_import_any?
      flash[:notice] = "Sie haben keine Importberechtigungen"
      redirect_to :controller => :start
    end
  end

  def upload
    if params[:sfile]
      #XML_API_URI sollte am Ende von config/environment.rb definiert werden, und ohne trailing slash angegeben werden, z.B. XML_API_URI = "http://localhost:3000"
      #Diese Datei ist im svn ignoriert, also muss die Konstante bei jedem Deployment neu gesetzt werden
      uri = URI.parse(XML_API_URI) #XML_API_URI sollte am Ende von config/environment.rb definiert werden (s.o.)
      init_header = {'user' => theUser(session).loginname, 'Accept' => '*/*'}
      http = Net::HTTP.new(uri.host,uri.port)
      if uri.scheme == "https"
         http.use_ssl = true
         http.verify_mode = OpenSSL::SSL::VERIFY_NONE
      end 
      http.start
      req_upload = http.request_post("#{uri.path}/import/#{params[:mode]}",params[:sfile][:uploaded_file].read(),init_header)
      http.finish
      case req_upload
        when Net::HTTPSuccess then @result = JSON(req_upload.body)
        else @result = req_upload.body
      end
    else
      flash[:notice] = "<b style='color:red'>Bitte wählen Sie zunächst eine Datei für den Import aus.</b>".html_safe
      redirect_to :action => :index
    end
  end

end
