# vim: ts=2 sw=2 et
class API::V1::ImportController < ApplicationController
  before_filter :restrict_access
  respond_to :json

  include ApplicationHelper
  require "base64"

  #Encoding.default_external = Encoding::UTF_8

  def index
    respond_to do |format|
      format.json { render :json => {} }
    end
  end

  def import_csv
    # erzeugen eines temp. Dateinamen. Tempsfiles werden nach Scope-Ende abgeräumt
    require 'tempfile'
    tf = Tempfile.new('ekommu-import', '/dev/shm')
    @session = { user: @user.id, tmpFilePath: tf.path }
    tf.close!

    # Datei mit Inhalt füllen
    #tf = File.new(@session[:tmpFilePath], 'w:ISO-8859-1')
    tf = File.new(@session[:tmpFilePath], 'w')
    tf.write(@content)
    tf.close
    data = { uploaded_file: @session[:tmpFilePath] }

    # Eigentlicher Importvorgang; Class CsvFile is defined in csv_file.rb
    @csv_file = CsvFile.new(data, @user, @mode, 43, @session)
    @csv_file.process_csv_file
    @csv_file.import
    
    File.delete(@session[:tmpFilePath])

    if(@csv_file.errors.count > 0)
      status = :unprocessable_entity
      json = { code: "ERR_HTML", position: 0, message: @csv_file.errors}
    else 
      status = :created
      json = { message: @csv_file.messages.join("\n") }
    end

    render json: json, status: status
    return
  end

  def import_xml
    #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' => @user.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/#{@mode}",@content,init_header)
    http.finish

    case req_upload
      when Net::HTTPSuccess then
        json = req_upload.body 
        status = :created
      else
        json = req_upload.body 
        status = :unprocessable_entity
    end

    render json: json, status: status
  end

  # post
  def create
    @meta = params[:metadata]
    @file = params[:file]

    @mode = @meta[:mode]
    begin
      @content = Base64.decode64(@file[:content])
      @content.force_encoding('utf-8').encode
    rescue Error => e
      render json: { message: "could not decode base64 content" }, status: :unprocessable_entity
      return
    end

    if @file[:filetype].downcase.eql? "csv"
      import_csv()
    elsif @file[:filetype].downcase.eql? "xml"
      import_xml()
    else
      render json: { message: "unsupported media type" }, status: :unsupported_media_type
      return
    end
    
  end

  private
  def restrict_access
    apikey="Api-Key"
    # Kein API-Key -> Zugriff verweigert
    if(!defined? request.headers[apikey] || !defined? params[:metadata])
      render json: { message: "no api-key provides: unauthorized" }, status: :unauthorized
      return
    elsif (!defined? params[:metadata] || !defined? params[:file])
      render json: { message: "missing metadata or file" }, status: :bad_request
      return
    # Falscher API-Key -> Zugriff verweigert
    elsif request.headers[apikey] != IMPORT_API_KEY
      render json: { message: "invalid api-key: access denied" }, status: :forbidden
      return
    end

    # Bestimmte Benutzernamen anhand des BL-Kürzel um spätere Importrechte zu überwachen
    state = params[:metadata][:federal_state].downcase
    username = "netzg-importer-" + state
    @user=User.where(loginname: username).take

    # Benutzer nicht gefunden -> Zugriff verweigert
    if @user == nil
      json = { message: "unkown username: "+username }
      render json: json, status: :forbidden
      return
    end
  end
end
