#!/usr/bin/env ruby
$: << ".."                      # Include .. in load path
require 'cppgen'

class MethodHolderGen < CppGen
  
  def initialize(outdir, amqp)
    super(outdir, amqp)
    @namespace="qpid::framing"
    @classname="MethodHolder"
    @filename="qpid/framing/MethodHolder"
  end

  def gen_max_size()
    # Generate program to generate MaxSize.h
    cpp_file("generate_#{@classname}MaxSize_h") {
      @amqp.amqp_methods.each { |m| include "qpid/framing/#{m.body_name}" }
      genl
      include "<algorithm>"
      include "<fstream>"
      genl
      genl "using namespace std;"
      genl "using namespace qpid::framing;"
      genl
      scope("int main(int, char** argv) {") {
        genl "size_t maxSize=0;"
        @amqp.amqp_methods.each { |m|
          genl "maxSize=max(maxSize, sizeof(#{m.body_name}));" }
        gen <<EOS
ofstream out("#{@filename}MaxSize.h");
out << "// GENERATED CODE: generated by " << argv[0] << endl;
out << "namespace qpid{ namespace framing { " << endl;
out << "const size_t MAX_METHODBODY_SIZE=" << maxSize << ";" << endl;
out << "}}" << endl;
EOS
      }
    }
  end

  def gen_construct
    cpp_file(@filename+"_construct") {
      include @filename
      include "qpid/framing/MethodBodyConstVisitor.h"
      @amqp.amqp_methods.each { |m| include "qpid/framing/#{m.body_name}" }
      genl
      include "qpid/Exception.h"
      genl
      namespace(@namespace) {
        # construct function
        scope("void #{@classname}::construct(ClassId c, MethodId m) {") {
          scope("switch (c) {") {
            @amqp.amqp_classes.each { |c|
              scope("case #{c.index}: switch(m) {") {
                c.amqp_methods.each { |m|
                  genl "case #{m.index}: blob.construct(in_place<#{m.body_name}>()); break;"
                }
                genl "default: throw Exception(QPID_MSG(\"Invalid method id \" << m << \" for class #{c.name} \"));"
              }
              genl "break;"
            }
            genl "default: throw Exception(QPID_MSG(\"Invalid class id \" << c));"
          }
        }
        # CopyVisitor
        struct("#{@classname}::CopyVisitor", "public MethodBodyConstVisitor") {           genl "MethodHolder& holder;"
          genl "CopyVisitor(MethodHolder& h) : holder(h) {}"
          @amqp.amqp_methods.each { |m|
            genl "void visit(const #{m.body_name}& x) { holder.blob=x; }"
          }
        }
        genl
        # operator=
        scope("#{@classname}& MethodHolder::operator=(const AMQMethodBody& m) {") {
          genl "CopyVisitor cv(*this); m.accept(cv); return *this;"
        }
      }}
  end

  def generate
    gen_max_size
    gen_construct
  end
end

MethodHolderGen.new(Outdir, Amqp).generate();

