require("munit")

function test_undo()
  doc = editor.new_doc()
  tassert_eq(doc.get_text(), '')
  doc.begin_user_action()
  doc.append_text('blah')
  tassert_eq(doc.get_text(), 'blah')
  doc.append_text('halb')
  tassert_eq(doc.get_text(), 'blahhalb')
  doc.end_user_action()
  tassert_eq(doc.can_redo(), false)
  tassert_eq(doc.can_undo(), true)
  doc.undo()
  tassert_eq(doc.can_redo(), true)
  tassert_eq(doc.can_undo(), false)
  tassert_eq(doc.get_text(), '')
  doc.redo()
  tassert_eq(doc.get_text(), 'blahhalb')
  tassert_eq(doc.can_redo(), false)
  tassert_eq(doc.can_undo(), true)

  doc.begin_non_undoable_action()
  doc.set_text('foobar')
  doc.end_non_undoable_action()
  tassert_eq(doc.get_text(), 'foobar')
  tassert_eq(doc.can_redo(), false)
  tassert_eq(doc.can_undo(), false)
  doc.undo()
  tassert_eq(doc.get_text(), 'foobar')
  tassert_eq(doc.can_redo(), false)
  tassert_eq(doc.can_undo(), false)
  doc.redo()
  tassert_eq(doc.get_text(), 'foobar')
  tassert_eq(doc.can_redo(), false)
  tassert_eq(doc.can_undo(), false)

  doc.set_modified(false)
  doc.close()
end

function test_edit()
  doc = editor.new_doc()
  tassert(doc.is_empty())
  tassert_eq(doc.get_text(), '')
  doc.set_text('foo')
  tassert(not doc.is_empty())
  tassert_eq(doc.get_text(), 'foo')
  doc.clear()
  tassert_eq(doc.get_text(), '')
  tassert(not doc.is_empty())
  doc.set_text('foo')
  doc.select_all()
  doc.copy()
  doc.paste()
  tassert_eq(doc.get_text(), 'foo')
  tassert(not doc.is_empty())
  doc.paste()
  tassert_eq(doc.get_text(), 'foofoo')
  doc.select_all()
  doc.cut()
  tassert_eq(doc.get_text(), '')
  tassert(not doc.is_empty())
  doc.paste()
  tassert_eq(doc.get_text(), 'foofoo')

  doc.set_modified(false)
  doc.close()
end

function read_file(filename)
  local f = assert(io.open(filename, 'rb'))
  local t = f:read("*all")
  f:close()
  return t
end

function save_file(filename, content)
  local f = assert(io.open(filename, 'wb'))
  f:write(content)
  f:close()
end

function test_file()
  doc = editor.new_doc()
  filename1 = moo.tempnam()
  filename2 = moo.tempnam()

  tassert(not _moo.path.exists(filename1))
  tassert(not _moo.path.exists(filename2))

  tassert(doc.is_untitled())
  doc.set_text('foobar')
  tassert(doc.save_as(moo.SaveInfo.new(filename1)))
  tassert(not doc.is_untitled())

  tassert(doc.get_filename() == filename1)
  tassert(read_file(filename1) == 'foobar')

  doc.set_text('blahfoo')
  tassert(doc.save_copy(moo.SaveInfo.new(filename2)))
  tassert(doc.get_filename() == filename1)
  tassert(read_file(filename1) == 'foobar')
  tassert(read_file(filename2) == 'blahfoo')

  tassert(doc.save())
  tassert(read_file(filename1) == 'blahfoo')

  tassert(editor.reload(doc))
  save_file(filename1, 'boomboom')
  tassert(editor.reload(doc))
  tassert(doc.get_text() == 'boomboom')

  tassert(editor.save_copy(doc, moo.SaveInfo.new(filename2)))
  tassert(read_file(filename2) == 'boomboom')

  tassert(doc.close())
end

test_undo()
test_edit()
test_file()
