-- states and stuff for local devices.
function printDict(data)
  for i, v in pairs(data) do
    print(tostring(i).." - "..tostring(v))
  end
end

local delay = 0.055 -- delay between each chunk of bits(each pulse, anything below 0.055 is unreliable)
-- 0.055 seconds per bit, 8 bits per character + 16 bit header and 8 bit footer
-- 4 characters(32 bits) would then take 1.6 seconds + header/footer which is an extra 1.2 seconds, 2.8 seconds in total.
-- travel time is message in bits * amount of gateways it has to pass through plus the transmitter, gateways = routers/masts


--server id and shit
local sID = 1
local s_recList = {1,16,256,4096}
local s_rec = s_recList[sID]
local s_trg = s_rec * 2

local s_sList = {4,64,1024,16384}
local s_sRec = s_sList[sID]
local s_sTrg = s_sRec * 2

local clients_router = {}

for i=1,4 do
	newrouter = {id=i, gID=0, rec=s_recList[i], trg=s_recList[i]*2, sRec=s_sList[i], sTrg=s_sList[i]*2, bitCnt=0, curByte=0, tags={}, bitList={}, byteList={}}
	table.insert(clients_router, newrouter)
end

for i,v in pairs(clients_router) do
	v.tags = {
	["C"]={0,1,0,0,0,0,1,1}
	}
end


local msgList = {}
local firstrun = true
local rC = 0 -- recieve colour
local tC = 0 -- trigger colour
local curMode = 1 -- 1 = router, 2 = mast
local sending = false

local clients_new = {}
local recList = {1,16,256,4096}
local sList = {4,64,1024,16384}

local speaker = peripheral.wrap("left")

--populate with clients.
for i=1,4 do
	newclient = {id=i, gID=0, rec=recList[i], trg=recList[i]*2, sRec=sList[i], sTrg=sList[i]*2, bitCnt=0, curByte=0, tags={}, bitList={}, byteList={}}
	table.insert(clients_new, newclient)
end

clients_new[1].gID = 10
clients_new[2].gID = 11
clients_new[3].gID = 12
clients_new[4].gID = 13

for i,v in pairs(clients_new) do
	v.tags = {
	["C"]={0,1,0,0,0,0,1,1}
	}
end

local msgQueue = {}
--example message
--{id, host, size, src, dest, msg}
--{0, 0, 128, 0}
-- id = owner id(local)
-- host = 0/1, sent from client/router
-- to = specific destination?(0=everywhere and include loopback to sender, 1 = everywhere but where sent from, 2 = only local network)
-- src = client sent from(global id)
-- dest = actual client to be sent to
-- size = size in bits(to calculate time to send message
-- msg = list of bits

--example packet: header(tag), global id(ie 23 = (00010111) ) or 00000001 for send to all.
--when router distributes it checks if client has the tag first, then checks if the adress is correct(or irrelevant if 1) then sends to that client.

function binToDec(num)
	local bStr = ""
    while num > 0 do    
		local rem = modulo(num, 2)
		bStr = rem .. bStr
		num = (num-rem)/2
    --print("CurLimit: " .. bVal)
	end
	return bStr
end

function getBit(cL, c)
  local ret = 0
  if colors.test(cL, c) then
    ret = 1
  end
  return ret
end

function writeBit(cL,c)
  local ret = 0
  if colors.test(cL, c) then
    ret = 1
  end
  write(ret)
  return ret
end

function strSplit(text)
  local rList = {}
  for i = 1, string.len(text) do
   table.insert(rList,string.sub(text, i ,i) )    
  end
  return rList
end

function printC(sText) 
	local w, h = term.getSize() 
	local x, y = term.getCursorPos() 
	x = math.max(math.floor((w / 2) - (#sText / 2)), 0) 
	term.setCursorPos(x, y) 
	print(sText) 
end 

function writeC(sText) 
	local w, h = term.getSize() 
	local x, y = term.getCursorPos() 
	x = math.max(math.floor((w / 2) - (#sText / 2)), 0) 
	term.setCursorPos(x, y) 
	write(sText) 
end 

function printStats(dodebug)
	term.clear()
	term.setCursorPos(1,1)
	local w, h = term.getSize()
	local str_div = string.rep("-", w - string.len("-"))
	print(str_div)
	printC("|Profan's Server Module|")
	print("Mode: " .. curMode)
	print(str_div)
	
	print("|Message Queue|")
	if next(msgQueue) then
		for i,v in pairs(msgQueue) do
			local rhost = "client"
			local msg = ""
			
			for i,v in ipairs(v.msg) do
				msg = msg .. v end
			
			if v.host == 1 then rhost = "router" end
			print(" Sender: " .. rhost .. " " .. v.src .. " -> destination: " .. v.dst)
			print("	 Message length: " .. v.bitCnt .. ", locality: " .. v.to)
			--print("		msg: " .. msg)
			--id=v.id, host=rhost, bitCnt=msgLen, src=1, dst=dest, msg=msgL
		end
	end
	
	if dodebug then
		print ("debug!")
	end
	
	term.setCursorPos(1,h)
	print(str_div)
	
end

function addToQueue(value,queue)
	table.insert(queue, value)
end

function mSendBit(val)
  mastBlink()
  if val == "1" then
    rednet.broadcast("1")
  elseif val == "0" then
    rednet.broadcast("0")
  end
  --monitor.write(val)
end

local mBusy = false
local mBitCnt = 0
local mBitStr = ""
local mCurByte = 0
local mSendQueue = {}
local num = 1

function mastBlink()
  if num == 1 then
    num = 2
	redstone.setOutput("right",true)
	sleep(delay)
	redstone.setOutput("right",false)
  elseif num == 2 then
    num = 1
 	redstone.setOutput("left",true)
	sleep(delay)
	redstone.setOutput("left",false) 
  end
end

function runMastServer(side)
  rednet.open(side)
  id, msg = rednet.receive()
  print(id .. msg)
  mastBlink()
  
  mBusy = true
  mCurByte = bit.bor(mCurByte, bit.blshift(tonumber(msg), 7 - mBitCnt))
  mBitCnt = mBitCnt + 1
  mBitStr = mBitStr .. msg
  
  if mBitCnt == 8 then
	if mCurByte == 0 then
		table.insert(mSendQueue, mBitStr)
		printStats("mast")
		mBitStr = ""
	end
	mCurByte = 0
	mBitCnt = 0
  end
  
  mBusy = false
  return true
end

function tableMerge(t1,t2)
	for k,v in pairs(t2) do t1[k] = v end
	return t1
end

--example message
--{id, host, size, src, dest, msg}
--{0, 0, 128, 0}
-- id = owner id(local)
-- host = 0/1, sent from client/router
-- to = specific destination?(0=everywhere and include loopback to sender, 1 = everywhere but where sent from, 2 = only local network)
-- src = client sent from(global id)
-- dest = actual client to be sent to
-- size = size in bits(to calculate time to send message
-- msg = list of bits

--example packet: header(tag), global id(ie 23 = (00010111) ) or 00000001 for send to all.
--when router distributes it checks if client has the tag first, then checks if the adress is correct(or irrelevant if 1) then sends to that client.

local tmpList = {}

function reverse(t)
  local nt = {} -- new table
  local size = #t + 1
  for k,v in ipairs(t) do
    nt[size - k] = v
  end
  return nt
end

function tobits(num)
    local t={}
    while num>0 do
        rest=num%2
        t[#t+1]=rest
        num=(num-rest)/2
    end
    t = reverse(t)
    return table.concat(t)
end

function bin(dec)
        local result = ""
       
        repeat
                local divres = dec / 2
                local int, frac = math.modf(divres)
                dec = int
                result = math.ceil(frac) .. result
        until dec == 0
       
        return result
end
function hex(dec)
        local result = ""
        local base16 = {"A","B","C","D","E","F"}
       
        repeat
                local remainder = dec % 16
                if remainder >= 10 then
                        remainder = base16[remainder - 9]
                end
                result = remainder .. result
               
                dec = math.modf(dec / 16)
        until dec == 0
       
        return result
end

function padValue(str, len)
  local rS = ""
  if string.len(str) < len then
    rS = string.rep("0", len - string.len(str))
    rS = rS .. str
  else
    rS = str
  end  
  return rS
end


function runServer(side)

  if firstrun then
	printStats()
	firstrun = false
  end
  
  if side == "back" then 
	clients_local = tableCopy(clients_router)
  end

  while os.pullEvent("redstone") do
    for i, v in pairs(clients_local) do	
	  if (v.id ~= sID and side == "back") or side == "bottom" then
		  local trig = v.sTrg
		  local recv = v.sRec
		  local bitCnt = 0
		  local bitList = {}
		  
		  local tBitCnt = 0
		  local input = rs.getBundledInput(side)
		  if colors.test(input, trig) then
			local mInput = writeBit(input, recv)
			v.curByte = bit.bor(v.curByte, bit.blshift(mInput, 7 - v.bitCnt)) 
			v.bitCnt = v.bitCnt + 1                               
			if v.bitCnt == 8 then
			  table.insert(v.byteList, v.curByte)
			  if v.curByte == 0 then
				--lat kod(fixa senare)
				local msgL = {}
				local source = v.byteList[2]
				local dest = v.byteList[3]
				
				for k, l in ipairs(v.byteList) do 
					table.insert(bitList, tobits(v.byteList[k])) 
				end
				
				for m, n in pairs(bitList) do
					while n:len() ~= 8 do n = padValue(n, 8) end 
					tBitCnt = tBitCnt + 8
					table.insert(msgL, n) -- tableMerge(msgL, n)
				end
				
				local nMsg = {id=v.id, host=side, bitCnt=tBitCnt, to=1, src=source, dst=dest, msg=msgL}
				table.insert(msgQueue, nMsg)
				v.bitList = {}
				v.byteList={}
				printStats()
				
			  end 
			  v.curByte = 0
			  v.bitCnt = 0
			  bitList = {}
			  bitCnt = 0
			end      
		  end
		end 
	end
  end 
  return true
end

function setColor(side, color, val)
  local sOutput = rs.getBundledOutput(side)
  local output = colors.combine(sOutput,color)
  if val == true then
    rs.setBundledOutput(side, output)
  elseif val == false then
    rs.setBundledOutput(side,colors.subtract(output,color))
  end  
end

function sendBit(side, val, rec, trg)  
  if val == "1" then
    setColor(side, rec,true)
    setColor(side, trg,true)
    sleep(delay)
    setColor(side, rec,false)
    setColor(side, trg,false)
  elseif val == "0" then
    setColor(side, trg, true)
    sleep(delay)
    setColor(side, trg, false) 
  end
  --monitor.write(val)
end

function tableCopy(t)
	local u = {}
	for k, v in pairs(t) do u[k] = v end
	return setmetatable(u, getmetatable(t))
end

function tableClear(t)
	for k in pairs (t) do
		t [k] = nil
	end
end

function tprint (tbl, indent)
  if not indent then indent = 0 end
  for k, v in pairs(tbl) do
    formatting = string.rep("  ", indent) .. k .. ": "
    if type(v) == "table" then
      print(formatting)
      tprint(v, indent+1)
    else
      print(formatting .. v)
    end
  end
end

function getType(var,id)
	if var == 0 then local tmpClients = tableCopy(clients_new)
	elseif var == 1 then local tmpClients = tableCopy(clients_router) end 
	tmpClients[id] = {}
	return tmpClients
end

--example message
--{id, host, size, src, dest, msg}
--{0, 0, 128, 0}
-- id = owner id(local)
-- host = 0/1, sent from client/router(now in text)
-- to = specific destination?(0=everywhere and include loopback to sender, 1 = everywhere but where sent from, 2 = only local network)
-- src = client sent from(global id)
-- dest = actual client to be sent to
-- size = size in bits(to calculate time to send message
-- msg = list of bits

--example packet: header(tag), global id(ie 23 = (00010111) ) or 00000001 for send to all.
--when router distributes it checks if client has the tag first, then checks if the adress is correct(or irrelevant if 1) then sends to that client.
-- nMsg = {id=v.id, host=rhost, bitCnt=tBitCnt, to=1, src=source, dst=dest, msg=msgL}

local rC_c = 0
local sC_c = 0

function transmitData()
	if next(msgQueue) then
	sending = true
		for i,v in pairs(msgQueue) do
			sleep(delay)
			local tmpClients = tableCopy(clients_new)
			
			if v.to == 0 then
				--send to all, including sender!		
			elseif v.to == 1 then
				--send to all, minus sender!
				for k, l in pairs(tmpClients)do
					if v.id  ~= l.id and v.host == "bottom" then
						if v.dst == 1 or v.dst == l.gID then
							write("debug!")
							rC_c = colors.combine(rC_c, l.rec)
							sC_c = colors.combine(sC_c, l.trg)	
						end
					elseif v.id ~= l.id and v.host == "back" then
						if v.dst == 1 or v.dst == l.gID then
							rC_c = colors.combine(rC_c, l.rec)
							sC_c = colors.combine(sC_c, l.trg)
						end
					elseif v.id == l.id and v.host == "back" then
						if v.dst == 1 or v.dst == l.gID then
							rC_c = colors.combine(rC_c, l.rec)
							sC_c = colors.combine(sC_c, l.trg)
						end
					end
				end				
			elseif v.to == 2 then
				--send to all, except other routers and sender.
			end	
			
			local tmpMsg = strSplit(table.concat(v.msg))
			
			for m, n in ipairs(tmpMsg) do
				sleep(delay)
				sendBit("bottom", n, rC_c, sC_c)
				if v.id ~= sID and v.host ~= "back" then
					sendBit("back", n, s_sRec, s_sTrg)
				elseif v.id == sID and v.host ~= "back" then
					sendBit("back", n, s_sRec, s_sTrg)				
				end
				write(n)
			end
			rC_c = 0
			sC_c = 0	
			msgQueue[v] = nil
			printStats()	
		end		
		sending = false
		msgQueue = {}
		printStats()
	else
		return true
	end
end

local ret
while true do
  parallel.waitForAny(
    function()
      ret = runServer("bottom")
    end,
    function()
      ret = runServer("back")
    end,
    function()    
       if transmitData() then
        --print("true :I")
         sleep(0.0001)
       end
    end
  )
end
