import Foundation


class TextFile
{
	private var _hnd: UnsafeMutablePointer<FILE>
	private let _maxLength: Int

	init(fileURL: URL, maxLineLength: Int = 1024) throws
	{
		guard let f = fopen(fileURL.path, "r")
		else { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno)) }

		_hnd = f
		_maxLength = maxLineLength
	}

	deinit
	{
		fclose(_hnd)
	}

	struct LinesSequence: Sequence, IteratorProtocol
	{
		typealias Element = String

		private var _hnd: UnsafeMutablePointer<FILE>
		private var _buffer: [CChar]

		fileprivate init(_ handle: UnsafeMutablePointer<FILE>, _ maxLength: Int)
		{
			_hnd = handle
			_buffer = [CChar](repeating: 0, count: maxLength)
		}

		mutating func next() -> String?
		{
			guard fgets(&_buffer, Int32(_buffer.count), _hnd) != nil
			else
			{
				if feof(_hnd) != 0 { return nil }
				else { return nil }
			}
			let length = strcspn(_buffer, "\r\n")
			_buffer[length] = "\0".utf8CString[0]
			//if let pos = strchr(_buffer, Int32("\n".utf8CString[0])) { pos[0] = "\0".utf8CString[0] }
			return String(cString: _buffer)
		}
	}

	public var lines: LinesSequence { LinesSequence(_hnd, _maxLength) }
}
