#include "foo.h"

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <gmodule.h>
#include <epan/prefs.h>
#include <epan/packet.h>

/* forward reference */
void proto_register_foo();
void proto_reg_handoff_foo();
void dissect_foo(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree);

/* Define version if we are not building Wireshark statically */
#ifndef ENABLE_STATIC
G_MODULE_EXPORT const gchar version[] = "0.0";
#endif

static int proto_foo = -1;
static dissector_handle_t foo_handle;

#ifndef ENABLE_STATIC
G_MODULE_EXPORT void plugin_register(void)
{
   /* register the new protocol, protocol fields, and subtrees */
   if (proto_foo == -1) { /* execute protocol initialization only once */
      proto_register_foo();
   }
}

G_MODULE_EXPORT void plugin_reg_handoff(void){
   proto_reg_handoff_foo();
}
#endif

static int ett_foo = -1;

/* Setup protocol subtree array */
static int *ett[] = {
   &ett_foo
};

void proto_register_foo(void)
{
   module_t *module;

   if (proto_foo == -1)
   {
      proto_foo = proto_register_protocol (
         "Foo Protocol", /* name */
         "FOO",          /* short name */
         "foo"	         /* abbrev */
      );

      module = prefs_register_protocol(proto_foo, proto_reg_handoff_foo);
      proto_register_subtree_array(ett, array_length(ett));

      /* call the tsnc generated register function */
      Foo_register(proto_foo);
   }
}

void proto_reg_handoff_foo(void)
{
   static int Initialized=FALSE;

   /* register with wireshark to dissect udp packets on port 3001 */
   if (!Initialized) {
      foo_handle = create_dissector_handle(dissect_foo, proto_foo);
      dissector_add("udp.port", 3001, foo_handle);
   }
}

void dissect_foo(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
{
   if (check_col(pinfo->cinfo, COL_PROTOCOL))
      col_set_str(pinfo->cinfo, COL_PROTOCOL, "FOO");
   /* Clear out stuff in the info column */
   if (check_col(pinfo->cinfo,COL_INFO)) {
      col_clear(pinfo->cinfo,COL_INFO);
   }

   if (tree) { /* we are being asked for details */
      proto_item *ti;
      Foo        *msg;

      ti = proto_tree_add_item(tree, proto_foo, tvb, 0, -1, FALSE);

      tree = proto_item_add_subtree(ti, ett_foo);

      msg = ep_alloc(sizeof(Foo));

      /* call the tsnc generated dissect function */
      Foo_dissect(msg, proto_foo, tvb, 0, pinfo, tree);
   }
}
