--The start of big things
--

lkmsg = require("liblkmsg")
local kmsg={}
local kobj={}
local ktag={}

function kmsg.new()
   kmsg["socket"]=kmsg_new()
   kmsg["timeout"]=2
   kmsg["sequence"]=0
end

function kmsg.connect(this,host,port)
   this["host"]=host
   this["port"]=port
   kmsg_connect(this.socket,host,port)
end


function kmsg.show()
   print("Socket="..kmsg.socket)
   print("Host="..kmsg.host)
   print("Port="..kmsg.port)
   
end

function kmsg.msg(this,type)
   --print("Creating a new message of type "..type)
   --print("Object Socket="..this.socket)
   local msg = {}
   msg["type"]=type
   msg["add"]=kobj.add
   msg["objs"]={}
   msg["msgtags"]={}
   return msg
end

function kmsg.send(this,msg)
   msg["seq"]=kmsg.sequence
   kmsg.sequence = kmsg.sequence+1
   msg["msgtags"]={}
   for k,obj in ipairs(msg.objs) do
       table.insert(msg.msgtags,{tagid=obj.objid,tag_value=nil})
       for j,tag in ipairs(obj.tags) do
          table.insert(msg.msgtags,tag)
       end 
   end
   
   kmsg_send(this.socket,msg)
end

function kmsg.receive(this,metalist)
   local rxmsg = kmsg_receive(this.socket,this.timeout)
   if rxmsg ~= nil and rxmsg.msgtags ~= nil then
      rxmsg["objs"] = {}
      local obj = {}
      for k,tag in ipairs(rxmsg.msgtags) do
         if metalist[tag.tagid] ~= nil then
            if obj.objid ~= nil then
               table.insert(rxmsg.objs,obj)
            end
            obj={}
            obj["objid"]=tag.tagid
            obj["tags"]={}
         else
            if obj.objid ~= nil then
               table.insert(obj.tags,tag)
            end
         end  
      end
      if obj.objid ~= nil then
         table.insert(rxmsg.objs,obj)
      end
    
   end
   return rxmsg;
end

function kmsg.obj(this,objid)
   obj = {};
   obj["objid"] = objid
   obj["tags"] = {}
   obj["addTag"]=kobj.addTag
   return obj
end

function kobj.add(msg,obj)
   table.insert(msg.objs, obj)
end

function kobj.addTag(obj,tag_id,tag_value)
    local tag ={}
    tag["tagid"]=tag_id
    tag["tag_value"]=tag_value
    table.insert(obj.tags,tag)
end

  
return kmsg

