local ChatUtil = BaseClass("ChatUtil")

function ChatUtil.BinarySearchBySeqId(chatList, targetSeqId, nearest)
  if not targetSeqId or #chatList == 0 then
    return nil
  end
  local low, high = 1, #chatList
  while low <= high do
    local mid = math.floor((low + high) / 2)
    local midSeq = chatList[mid].seqId
    if midSeq == targetSeqId then
      return mid
    elseif targetSeqId > midSeq then
      low = mid + 1
    else
      high = mid - 1
    end
  end
  if not nearest then
    return nil
  end
  local leftIndex = high
  local rightIndex = low
  if leftIndex < 1 then
    return 1
  elseif rightIndex > #chatList then
    return #chatList
  end
  local leftDiff = math.abs(chatList[leftIndex].seqId - targetSeqId)
  local rightDiff = math.abs(chatList[rightIndex].seqId - targetSeqId)
  if leftDiff <= rightDiff then
    return leftIndex
  else
    return rightIndex
  end
end

return ChatUtil
