#include "PngWriter.h"

#include "Image.h"

#ifdef HAS_LIBPNG
#include <png.h>
#include "PngWriterLibPng.h"
#else
#include "PngWriterBasic.h"
#endif
#include <stdio.h>

PngWriter::PngWriter()
{
#ifdef HAS_LIBPNG
    mImpl = std::make_unique<PngWriterLibPng>();
#else
    mImpl = std::make_unique<PngWriterBasic>();
#endif
}

std::unique_ptr<PngWriter> PngWriter::Create()
{
    return std::make_unique<PngWriter>();
}

void PngWriter::SetPath(const std::string& path)
{
    mImpl->setPath(path);
}

void PngWriter::Write(const std::unique_ptr<Image>& image) const
{
    mImpl->write(image);
    //auto fp = fopen(mPath.c_str(), "wb");

    //auto png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
    //auto info_ptr = png_create_info_struct(png_ptr);

    //if (setjmp(png_jmpbuf(png_ptr)))
    //{
    //    return;
    //}
    //png_init_io(png_ptr, fp);


    //if (setjmp(png_jmpbuf(png_ptr)))
    //{
    //    return;
    //}
    //auto color_type = PNG_COLOR_TYPE_RGB;
    //png_set_IHDR(png_ptr, info_ptr, image->GetWidth(), image->GetHeight(),
    //             image->GetBitDepth(), color_type, PNG_INTERLACE_NONE,
    //             PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);

    //png_write_info(png_ptr, info_ptr);

    //if (setjmp(png_jmpbuf(png_ptr)))
    //{
    //    return;
    //}

    //png_bytep* row_pointers = (png_bytep*)malloc(sizeof(png_bytep) * image->GetHeight());
    //auto row_size = image->GetBytesPerRow();
    //for(unsigned jdx=0;jdx<image->GetHeight();jdx++)
    //{
    //    row_pointers[jdx]=(png_byte*)malloc(sizeof(png_byte)*row_size);
    //    for(unsigned idx=0;idx<row_size;idx++)
    //    {
    //        row_pointers[jdx][idx] = image->GetByte(idx, jdx);
    //    }
    //}
    //png_write_image(png_ptr, row_pointers);
    //if (setjmp(png_jmpbuf(png_ptr)))
    //{
    //    return;
    //}

    //png_write_end(png_ptr, nullptr);

    //for (unsigned y=0; y<image->GetHeight(); y++)
    //{
    //    free(row_pointers[y]);
    //}
    //free(row_pointers);

    //fclose(fp);
    //return;
}
