#pragma once
#include "String.h"
#include "Text.h"

class File {
	FILE* ptr;
public:
	File(String* name) {
		ptr = fopen(name->getCharArray(), "r");
	}
	File(const char* name) {
		ptr = fopen(name, "r");
	}
	File(const String& name, const String& text) {
		ptr = fopen(name.getCharArray(), "w");
		fprintf(ptr, "%s", text.getCharArray());
	}
	~File() {
		Close();
	}
	void Close() {
		if (ptr != NULL) {
			fclose(ptr);
			ptr = NULL;
		}
	}
	String read() {
	    int c;
	    String res;
	    do {
            c = fgetc(ptr);
            switch (c){
                case EOF:
                    break;
                default:
                    res.addChar(c);
                    break;
            }
        } while (c!=EOF);
	    return res;
	}
	Text* readLines() {
		Text* lines = new Text();
		int c;
		String* line = NULL;
		bool lineStarted = false;
		do {
			c = fgetc(ptr);
			if (lineStarted) {
				switch (c) {
				case '\r':
					break;
				case '\n':
				case EOF:
					lines->add(line);
					line = NULL;
					lineStarted = false;
					break;
				default:
					line->addChar((char)c);
					break;
				}
			}
			else {
				switch (c) {
				case '\r':
					break;
				case '\n':
					line = new String();
					lines->add(line);
					line = NULL;
					break;
				case EOF:
					break;
				default:
					line = new String();
					line->addChar((char)c);
					lineStarted = true;
					break;
				}
			}
		} while (c != EOF);
		return lines;
	}
};