#include "stdafx.h"
#include "FileOutputBuffer.h"
const int MAXPEROUTPUTLINE = 10000;
const unsigned int MINBUFFERSIZE = 100000;

FileOutputBuffer::FileOutputBuffer(void)
{
    this->caBuffer = NULL;
    this->caBufp = NULL;//pointer point to a location of caBuffer, (don't delete)
    this->uiCapacity = 0;
    this->uiSize = 0;
}
FileOutputBuffer::FileOutputBuffer(unsigned int uiCapacity, ofstream* pofile)
{
    this->uiCapacity = uiCapacity;
    if (uiCapacity < MINBUFFERSIZE) {
        cout << "The buffer is set to the minimum" << MINBUFFERSIZE << endl;
        this->uiCapacity = MINBUFFERSIZE;
    }
    this->caBuffer = new char [uiCapacity];
    memset(this->caBuffer, 0x00, sizeof(char)*uiCapacity);
    this->pofile = pofile;
    this->uiSize = 0;
    this->caBufp = this->caBuffer;//point to start2
}
FileOutputBuffer::~FileOutputBuffer(void)
{
    if (this->uiSize > 0) {
        this->fflush();
        // (*this->pofile) << "\n";
    }

    if (this->pofile !=  NULL) {
        if ((*this->pofile).good()) {
            (*this->pofile).close();
        }
    }
    delete [] this->caBuffer;
}
void FileOutputBuffer::UpdateSize()
{
    for (; this->uiSize < this->uiCapacity; this->uiSize++) {
        if (this->caBuffer[this->uiSize] == 0) { //if it firstly meet to unwritten part
            this->caBufp = &(this->caBuffer[this->uiSize]);
            break;
        }
    }
    if (this->uiSize > this->uiCapacity - MAXPEROUTPUTLINE) { //write to file before it is overflow
        this->fflush();
    }
}
void FileOutputBuffer::fflush(void)
{
    (*pofile) << this->caBuffer; // output to file
    memset(this->caBuffer, 0x00, sizeof(char)*uiCapacity);//flush buffer
    this->uiSize = 0;
    this->caBufp = this->caBuffer;//point to start
}
void FileOutputBuffer::removeEndBlankLine(void)
{
    while (this->uiSize > 0) {
        //if the last character is a new line
        if (this->caBuffer[this->uiSize - 1] == '\n') {
            this->uiSize--;
            this->caBufp = &this->caBuffer[this->uiSize];
            this->caBufp[0] = 0;
        } else {
            break;
        }
    }
}

