--[[Dex chat |server| script writted by Bryan B aka incinirate. feel free to edit as much as you want, just give me credit please. Thanks for using DexChat]]

modem="back"
rednet.open(modem)
computers={}
users={}
notonline={}
deny=false
currtext=""
stop=false
sentcommand=false
banned={}
ubanned={}

shell.run("clear")
print("DexChat Server V4 Starting!")

function refreshBanned()
  for i=1,#banned do
    banned[i]=nil
  end
  bannedips=fs.open(shell.resolve("").."/banlist","r")
  if bannedips ~= nil then
    tmpbnd = nil
    tmpbnd = bannedips.readLine()
    if tmpbnd ~= nil then
      while tmpbnd ~= nil do
        table.insert(banned,tmpbnd)
	    tmpbnd = bannedips.readLine()
      end
    end
    bannedips.close()
  end
  bannedusr=fs.open(shell.resolve("").."/ubanlist","r")
  if bannedusr ~= nil then 
    tmpbnd = bannedusr.readLine()
    if tmpbnd ~= nil then
      while tmpbnd ~= nil do
        table.insert(ubanned,tmpbnd)
        tmpbnd = bannedusr.readLine()
      end
    end
    bannedusr.close()
  end
end

refreshBanned()

function isBanned(usr,id)
  for i=1,#banned do
    if tostring(id)==tostring(banned[i]) then
	  return true
	end
  end
  for i=1,#ubanned do
    if tostring(usr)==tostring(ubanned[i]) then
	  return true
	end
  end
  return false
end

function isConnected(im)
  for i=1,#computers do
    if computers[i]==im then
      return true
    end
  end
  return false
end

function backspace()
  cx,cy=term.getCursorPos()
  local tempchars={}
  local finalchars={}
  for i=1,#currtext do
    a=currtext:sub(i, i)
    table.insert(tempchars, a)
  end
  for i=1,#tempchars-1 do
    table.insert(finalchars,tempchars[i])
  end
  currtext=""
  for i=1,#finalchars do
    currtext=currtext..finalchars[i]
  end
  term.setCursorPos(1,cy)
  term.clearLine()
  write(currtext)
end

main=function()
  sentcommand=false
  id,message=rednet.receive()
  term.clearLine()
  cx,cy=term.getCursorPos()
  term.setCursorPos(1,cy)
  print("Message from "..id..". Message: "..message)
  iter = string.gmatch(message, "%P+")
  u = iter()
  k = iter()

  citer = string.gmatch(message, "%S+")
  cu = citer()
  ck = citer()
  ch = citer()

  if cu ~= nil then
    v=1
    cchrs={}
    for i=1,#cu do tmpchr=string.sub(cu, i, i) table.insert(cchrs,tmpchr) end
    repeat
    v=v+1
    if cchrs[v]=="/" then
      sentcommand=true
    end
    until cchrs[v]=="/" or v==#cchrs
    if cu == "/list" then
      userlist=""
      if users[1] ~= nil then
        userlist=userlist..users[1]
        for i=2,#users do
          userlist=userlist..", "..users[2]
        end
        rednet.send(id,"Connected users: "..userlist)
      else
        rednet.send(id,"No users are connected.")
      end
      sentcommand=true
    end

  end

  if k~=nil then print("Found as, "..u.." and "..k) end
  if k=="Connecting" then
    if isBanned(u,id) then
	  print("Sending: You are banned from this server TO "..id)rednet.send(id,"You are banned from this server")
	  deny=true
	end
    for i=1,#computers do
      if id==computers[i] then
        deny=true
      end
      if u==users[i] then
        deny=true
      end
    end
    if deny==true then sleep(0.25) print("Sending: Denied TO "..id)rednet.send(id,"Denied")
    else
      print(u.." is connecting")
      table.insert(computers,id)
      table.insert(users,u)
      for i=1,#notonline do
        if notonline[i]==id then
          table.remove(notonline,i)
        end
      end
      for i=1,#computers do
        sleep(0.25) print("Sending: "..u.."has connected! To all computers") rednet.send(computers[i],u.." has connected!")
      end
    end
   else if k=="disconnect" then
     
     
	print(u)
        for i=1,#computers do
                print(u)
                if u~=computers[i] then print(u.."~="..computers[i]) end
		print("computer "..i..":"..computers[i])
                print("user "..i..":"..users[i])
                disser=nil
		if tonumber(u)==tonumber(computers[i]) then disser=i end
  if tonumber(u)==tonumber(notonline[i]) then disser=nil end
	end
	if disser ~= nil then
                print("Disser is not NIL")
                print(disser)
		print("Disconnecting "..users[disser])
		for j=1,#computers do
			rednet.send(computers[j],users[disser].." has disconnected.")
		end
  table.insert(notonline,disser)
		table.remove(computers,disser)
		table.remove(users,disser)
	end

   
  else
    if isConnected(id) then
      if sentcommand == false then
        for i=1,#computers do
          print("Sending: "..message.." to all computers.")
          rednet.send(computers[i],message)
          sentcommand = false
        end
      end
    else
      if sentcommand == false then
        rednet.send(id,"You are not connected.")
        sentcommand = false
      end
      end
    end
  end
end


readtxt = function()
  term.clearLine()
  x,y = term.getCursorPos()
  term.setCursorPos(1,y)
  write(currtext)
  while true do
    e,par1 = os.pullEvent()
    if e == "char" then
      currtext=currtext..par1
      write(par1)
    end
    if e == "key" then
      if par1==14 then
        backspace()
      end
      if par1==28 then
        got = currtext
        currtext=""
        break
      end
    end
  end
end

function activateCommand(com)
  args = {}
  for arg in string.gmatch(com,"%S+") do 
  table.insert(args,arg) 
  end

  print("")  
  if args[1] == "/kick" then
    if args[2] ~= nil then
      foundu=false
      for i=1,#users do
        if users[i] == args[2] then
          foundu=true
          if args[3] == nil then
          rednet.send(computers[i],"You were kicked.")
          for j=1,#computers do
            if j~=i then
              rednet.send(computers[j],users[i].." was kicked.")
            end
          end
          print("Kicked "..args[2]..".")
          else
          rednet.send(computers[i],"You were kicked for "..args[3])
          for j=1,#computers do
            if j~=i then
              rednet.send(computers[j],users[i].." was kicked for "..args[3])
            end
          end
          print("Kicked "..args[2].." for "..args[3]..".")
          end
          table.insert(notonline,i)
          table.remove(computers,i)
          table.remove(users,i)
        end
      end
      if foundu == false then
        print("Did not find a user by the name of "..args[2])
        print("Usage: /kick <username> [reason]")
      end
    else
      print("Usage: /kick <username> [reason]")
    end
  else if args[1] == "/help" then
    print(" ")
    print("/help -View Commands")
    print("/list -Lists connected users")
    print("/kick <username> [reason] -Kicks a user")
	print("/ban <username> [reason] -Bans a user")
    print("/stop -Stops the server")
    print(" ")
  else if args[1]=="/list" then
    userlist=""
    if users[1] ~= nil then
      userlist=userlist..users[1]
      for i=2,#users do
        userlist=userlist..", "..users[2]
      end
      print("Connected users: "..userlist)
    else
      print("No users are connected.")
    end
  else if args[1]=="/stop" then
    stop=true
    for i=1,#computers do
      rednet.send(computers[i],"Server Stopped. Please press DELETE to exit.")
    end
  else if args[1]=="/ban" then
    if args[2] ~= nil then
      foundu=false
      for i=1,#users do
        if users[i] == args[2] then
          foundu=true
		  banlist = fs.open(shell.resolve("").."/banlist","a")
		  print(banlist)
		  banlist.writeLine(tostring(computers[i]))
		  ubanlist = fs.open(shell.resolve("").."/ubanlist","a")
		  ubanlist.writeLine(users[i])
		  banlist.close()
		  ubanlist.close()
          if args[3] == nil then
          rednet.send(computers[i],"You were banned.")
          for j=1,#computers do
            if j~=i then
              rednet.send(computers[j],users[i].." was banned.")
            end
          end
          print("Banned "..args[2]..".")
          else
          rednet.send(computers[i],"You were banned for "..args[3])
          for j=1,#computers do
            if j~=i then
              rednet.send(computers[j],users[i].." was banned for "..args[3])
            end
          end
          print("Banned "..args[2].." for "..args[3]..".")
          end
          table.insert(notonline,i)
          table.remove(computers,i)
          table.remove(users,i)
		  refreshBanned()
        end
      end
      if foundu == false then
        print("Did not find a user by the name of "..args[2])
        print("Usage: /ban <username> [reason]")
      end
    else
      print("Usage: /ban <username> [reason]")
    end
  else
    print("Command not found. Try using /help")
  end
end
end
end
end
end

while true do
  event = parallel.waitForAny(main,readtxt)
  if got ~= nil then
  if tonumber(event) == 2 then
  activateCommand(got)
  end
  end
  sleep(0.1)
  if stop==true then
    break
  end 
end
print("DexChat Server Stopping...")
print("DexChat Server Stopped.")