if not pigeonF and (not lOS or not lOS.processes) then
	_G.pigeonF = true
	shell.run("pastebin run TUn3tG5v pastebin run 0kaGJXZ5")
	return
end

if not lUtils then
	shell.run("pastebin run zZszFdWe")
end

local mMax = 30

local function swap()
    local fg,bg = term.getTextColor(),term.getBackgroundColor()
    term.setTextColor(bg)
    term.setBackgroundColor(fg)
end

local function newMsg(msg,name,x,y,maxWidth,first,txtcolor,scroll,namecolor,date)
    if date then
        lOS.pDebug.date = date
    end
    local txt
    if not txtcolor then
        txt = colors.white
    else
        txt = txtcolor
    end
        local l = {""}
    local width = name:len()+2
    local pDate = true
    if date and first then
	local d,m,y = tonumber(os.date("%d")),tonumber(os.date("%m")),tonumber(os.date("%Y"))
	if d == date.d and m == date.m and y == date.y then
		width = width+6 -- TEMP UNTIL I FIGURE OUT HOW TO GET CURRENT DAY (IF NOT CURRENT DAY PRINT DATE INSTEAD OF TIME)
	else
		pDate = false
		width = width+11
	end
    end
    for word in string.gmatch(msg,"%S+") do
        local a = l[#l].." "..word
        if #a+1 > maxWidth then
            l[#l+1] = ""
        elseif #a+1 > width then
            width = a:len()+1
        end
        l[#l] = l[#l].." "..word
    end
    local w,h = term.getSize()
    if scroll ~= false then
        if first then
            while y+#l >= h-1 do
                term.scroll(1)
                y = y-1
            end
        elseif not first then
            while y+#l >= h do
                term.scroll(1)
                y = y-1
            end
        end
    end
    --y = y-#l
    if not first then
    	--y = y+1
    end
    term.setCursorPos(x,y)
    -- draw msg box
    swap()
    if first then
    	term.setCursorPos(x-1,y)
        term.write("\143\143")
    else
        term.setCursorPos(x+1,y)
    end
    term.write(string.rep("\143",width))
    swap()
    local cY = 1
    if name and first then
        term.setCursorPos(x-1,y+cY)
        term.write("\130")
        swap()
        --swap()
        term.write(string.rep(" ",width+1))
        --swap()
        term.write("\138")
        --swap()
        term.setCursorPos(x+1,y+cY)
        local temp = term.getTextColor()
        if term.getBackgroundColor() == colors.cyan then
            term.setTextColor(colors.lightBlue)
        elseif name == "Moderator" then
            term.setTextColor(colors.red)
        else
            term.setTextColor(colors.lime)
        end
        term.write(" "..name)
	if date then
		term.setTextColor(colors.lightGray)
		if pDate then
			term.write(" "..string.format("%02d:%02d",date.H,date.M))
		else
			term.write(" "..string.format("%02d/%02d/%04d",date.d,date.m,date.y))
		end
	end
        term.setTextColor(temp)
        cY = cY+1
        swap()
    end
    swap()
    if #l > 1 then
        for t=1,#l-1 do
            term.setCursorPos(x,y+cY)
            if t == 1 and not (name and first) then
                --swap()
                term.write("\133")
                --swap()
                term.write(string.rep(" ",width))
                --swap()
                term.write("\138")
                --swap()
            else
                term.write(string.rep(" ",width+2))
            end
            term.setCursorPos(x+1,y+cY)
            local temp = term.getTextColor()
            term.setTextColor(txt)
            term.write(l[t])
            term.setTextColor(temp)
            cY = cY+1
        end
    end
    swap()
    term.setCursorPos(x,y+cY)
    term.write("\138")
    swap()
    term.setCursorPos(x+1,y+cY)
    term.write(string.rep(" ",width))
    swap()
    term.write("\133")
    swap()
    term.setCursorPos(x+1,y+cY)
    local temp = term.getTextColor()
    term.setTextColor(txt)
    term.write(l[#l])
    term.setTextColor(temp)
    term.setCursorPos(x,y+cY+1)
    swap()
end

local e = {}
local msgs = {}
local msg = function(u,m,col) msgs[#msgs+1] = {m,u,col} end
--msg("Person","Look at this beautiful area!")
--msg("Person","I was there yesterday.")
--msg("Other Person","Woah that's so amazing! I would love to go there someday...")
--msg("Noodle","Yeah indeed. Beautiful!")
msg("System","Loading messages...")
--local user = "Noodle"
local userID,user = lOS.userID,lOS.username
while not userID do
    userID,user = dofile("LevelOS/login.lua")
end
local temp = http.get("https://os.leveloper.cc/pigeon/pigeon.php",{Cookie=userID})
if temp.readAll() ~= "200" then
    lUtils.popup("Pigeon","An error has occured!",29,9,{"Quit"})
    return
end


local w,h = term.getSize()
local msgbox = lUtils.makeEditBox("msg",w,1)
local msgwin = window.create(term.current(),1,3,w,h-5)

local function timedif()
	return tonumber(os.date("%H"))-tonumber(os.date("!%H")),tonumber(os.date("%M"))-tonumber(os.date("!%M"))
end

local hdif,mdif = timedif()

local function retrieve()
    local answer = http.get("https://os.leveloper.cc/pigeon/chat.php",{Cookie=userID})
    local messages = answer.readAll()
    msgs = {}
    if not lOS.pDebug then
        lOS.pDebug = {}
    end
    for i=1,mMax do
        message,messages = lUtils.getField(messages,"msg")
        if message ~= nil then
            local nMsg = lUtils.getField(message,"content")
            local nSender = lUtils.getField(message,"sender")
            local nDate = lUtils.getField(message,"date")
            local pMsg = {nMsg,nSender}
            if nDate then
                pMsg.date = textutils.unserialize(nDate)
                pMsg.date.H,pMsg.date.M = pMsg.date.H+hdif,pMsg.date.M+mdif
                if pMsg.date.H >= 24 then
                    pMsg.date.H = pMsg.date.H-24
                    pMsg.date.d = pMsg.date.d+1
                end
            end
            table.insert(msgs,1,pMsg)
        else
            lOS.pDebug.msgs = msgs
            return
        end
    end
end

local function typemsg()
    while true do
        a = {lUtils.drawEditBox(msgbox,nil,nil,nil,nil,nil,nil,true,false)}
        if msgbox.lines[1] ~= "" and e[1] ~= "mouse_click" and userID then
            http.post("https://os.leveloper.cc/pigeon/send.php","message="..textutils.urlEncode(msgbox.lines[1]),{Cookie=userID})
            msg(user,msgbox.lines[1],colors.lightGray)
            msgbox.lines[1] = ""
        elseif msgbox.lines[1] ~= "" and e[1] ~= "mouse_click" and not userID then
            local dbg = {}
            for t=1,#a do
                dbg[#dbg+1] = tostring(a[t])
            end
            --msg("Debug",table.concat(dbg,", "))
            local rmsg = msgbox.lines[1]
            if string.find(rmsg,"/say ") then
                msg("Moderator",string.sub(rmsg,5))
            elseif string.find(rmsg,"/msg ") then
                msg("System",string.sub(rmsg,5))
            else
                msg(user,msgbox.lines[1])
            end
            local themsg = string.lower(msgbox.lines[1])
            msgbox.lines[1] = ""
            if string.find(themsg,"hey") or string.find(themsg,"hello") then
                os.sleep(0.5)
                msg("LevelOS","Heyyyy!")
            elseif string.find(themsg,"how are you") then
                os.sleep(0.5)
                msg("LevelOS","I'm good!! What about youu <3")
            --elseif string.find(themsg,"i'm ") or string.find(themsg,"im ") or string.find(themsg,"i am ") then
            end
        end
    end
end


local function refresh()
    while true do
        retrieve()
        os.sleep(2)
    end
end


local typecor = coroutine.create(typemsg)
local refcor = coroutine.create(refresh)
local scrollpos = 0
local scmax = 0

while true do
    term.setBackgroundColor(colors.white)
    term.clear()
    term.setBackgroundColor(colors.blue)
    term.setCursorPos(1,1)
    term.clearLine()
    term.setCursorPos(1,2)
    term.clearLine()
    term.setTextColor(colors.white)
    term.setCursorPos(1,1)
    print("\27 Main Chat ("..scrollpos.."/"..scmax..")")
    term.setTextColor(colors.lightGray)
    term.write("  Online")
    local w,h = term.getSize()
    msgwin.reposition(1,3,w,(h-5)+scrollpos)
    local owin = term.current()
    term.redirect(msgwin)
    term.setTextColor(colors.gray)
    term.setBackgroundColor(colors.white)
    term.clear()
    local function gp(t)
        local x,y = term.getCursorPos()
        if t == 1 then
            return 3
        else
            return y
        end
    end
    local w,h = term.getSize()
    local maxW = 15
    if math.floor(w/1.3) > maxW then
        maxW = math.floor(w/1.3)
    end
    local pr = print
    local function debugpr(...)
        pr(...)
        os.sleep(0.1)
    end
    term.setCursorPos(3,2)
    for m=1,#msgs do
        if msgs[m][2] == user then
            term.setTextColor(colors.cyan)
        else
            term.setTextColor(colors.gray)
        end
        local new
        if m > 1 then
            if msgs[m-1][2] == msgs[m][2] and not (msgs[m].date and msgs[m-1].date and (msgs[m].date.d ~= msgs[m-1].date.d or msgs[m].date.H ~= msgs[m-1].date.H or msgs[m].date.M >= msgs[m-1].date.M+5)) then
                new = false
            else
                new = true
            end
        else
            new = true
        end
        if msgs[m][2] == "System" then
            term.setBackgroundColor(colors.white)
            term.setTextColor(colors.white)
            newMsg(msgs[m][1],msgs[m][2],gp(1),gp(2),maxW,false,colors.red,nil,nil,msgs[m].date)
        else
            local col
            if msgs[m][3] == colors.lightGray then
                col = colors.lightGray
            end
            newMsg(msgs[m][1],msgs[m][2],gp(1),gp(2),maxW,new,col,nil,nil,msgs[m].date)
        end
    end
    scmax = (({term.getCursorPos()})[2]-({owin.getSize()})[2]+6)
    --newMsg("Look at this beautiful area!","Person",3,4,maxW,true)
    --print("")
--    print("")
    --newMsg("I was there yesterday.","Person",gp(1),gp(2),maxW,false)
    --print("\n\n")
    --print("")
    --newMsg("Woah that's so amazing! I would love to go there someday...","Other Person",gp(1),gp(2),maxW,true)
    --print("")
    --print("")
    --term.setTextColor(colors.blue)
    --newMsg("Yeah indeed. Beautiful!","Me",gp(1),gp(2),maxW,true)
    term.redirect(owin)
    local w,h = term.getSize()
    term.setCursorPos(1,h-2)
    term.setBackgroundColor(colors.lightGray)
    term.clearLine()
    term.setCursorPos(1,h-1)
    term.clearLine()
    term.setCursorPos(1,h)
    term.clearLine()
    term.setBackgroundColor(colors.lightGray)
    term.setTextColor(colors.white)
    newMsg(string.rep(".",w-14),"You",2,h-2,w-4,false,colors.white,false)
    msgbox.x = 4
    msgbox.y = h-1
    msgbox.width = w-14
    term.setTextColor(colors.blue)
    newMsg("Send","You",w-7,h-2,6,false,colors.white,false)
    --term.setCursorPos(1,h-4)
    term.setBackgroundColor(colors.white)
    term.setCursorPos(3,h-1)
    term.write(string.rep(" ",w-13))
    --if msgbox.lines[1] then
        --term.setCursorPos(3,h-1)
        --term.write(string.sub(msgbox.lines[1],1,w-13))
    --end
    term.setCursorPos(1,h-4)
	local dX,dY
	local _,totalHeight = term.getSize()
    while true do
        if e and not (e[1] and string.find(e[1],"mouse")) then
            coroutine.resume(typecor,unpack(e))
        end
        if e then
            coroutine.resume(refcor,unpack(e))
        end
        e = {os.pullEvent()}
        --if e[1] ~= "timer" then
        --coroutine.resume(typecor,table.unpack(e))
		--if mobile then
			if e[1] == "mouse_click" then
				dX,dY = e[3],e[4]
			elseif e[1] == "mouse_drag" and dX and dY then
				local nx,ny = e[3],e[4]
				if e[4] ~= dY then
					e = {"mouse_scroll",ny-dY}
				end
				dX,dY = nx,ny
			elseif e[1] == "mouse_up" then
				dX,dY = nil,nil
			end
		--[[if mobile then
			local w,h = term.getSize()
			if mobile.isKeyboardOpen() and h >= totalHeight then
				LevelOS.self.window.win.reposition(1,2,w,totalHeight-21)
			elseif not mobile.isKeyboardOpen() and h < totalHeight then
				LevelOS.self.window.win.reposition(1,2,w,totalHeight)
			end
		end]]
        if e[1] == "key_up" or e[1] == "key" or e[1] == "char" then
            --coroutine.resume(typecor,table.unpack(e))
            if e[1] == "key_up" and e[2] == keys.enter then
                break
            end
        else
            if e[1] == "mouse_scroll" then
                if scrollpos-e[2] >= 0 and scrollpos-e[2] <= scmax then
                    scrollpos = scrollpos-e[2]
				elseif scrollpos-e[2] > scmax then
                    if msgs[1][2] ~= "System" then
                    	table.insert(msgs,1,{"Loading messages...","System"})
                        mMax = mMax+15
                    end
                elseif scrollpos-e[2] < 0 then
                    mMax = 30
                end
            end
            break
        end
        --end
    end
end