require 'base64'
require_relative '../wendelin_client'
require_relative '../dataset_utils'

module Embulk
  module Output

    class Wendelin < OutputPlugin
      Plugin.register_output("wendelin", self)

      def self.transaction(config, schema, count, &control)
	task = {
	  "erp5_url" => config.param("erp5_url", :string),
	  "user" => config.param("user", :string, defualt: nil),
	  "password" => config.param("password", :string, default: nil),
	  "path_prefix" => config.param("path_prefix", :string,  :default => nil),
	}
	task_reports = yield(task)
	next_config_diff = {}
	@logger = LogManager.instance()
	if task_reports.length > 0
	  @logger.info("Your ingested files will be available in the site in a few minutes. Thank for your patience.", print=TRUE)
	else
	  @logger.info("No new files where processed for ingestion.", print=TRUE)
	end
	return next_config_diff
      end

      def init
	credentials = {}
	@erp5_url = task["erp5_url"]
	@user = task["user"]
	@password = task["password"]
	@logger = LogManager.instance()
	@wendelin = WendelinClient.new(@erp5_url, @user, @password)
      end

      def close
      end

      def add(page)
	page.each do |record|
	  supplier = (record[0].nil? || record[0].empty?) ? "default" : record[0]
	  dataset = (record[1].nil? || record[1].empty?) ? "default" : record[1]
	  filename = record[2]
	  extension = record[3]
	  eof = record[5]
	  data_chunk = record[4]
	  size = record[6]
	  hash = record[7]
	  begin
	    if eof == DatasetUtils::DELETE
	      reference = [dataset, filename, extension].join(DatasetUtils::REFERENCE_SEPARATOR)
	      @wendelin.delete(reference)
	    elsif eof == DatasetUtils::RENAME
	      reference = [dataset, filename, extension].join(DatasetUtils::REFERENCE_SEPARATOR)
	      @wendelin.rename(reference, record[4].to_s)
	    else
	      reference = [supplier, dataset, filename, extension, eof, size, hash].join(DatasetUtils::REFERENCE_SEPARATOR)
	      split = eof != ""
	      if not @wendelin.ingest(reference, data_chunk, split)
		raise "could not ingest"
	      end
	    end
	  rescue Exception => e  
	    raise e
	    @logger.error(e.backtrace)
	  end
	end
      end

      def finish
      end

      def abort
      end

      def commit
	task_report = {}
	return task_report
      end
    end

  end
end
