// This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2016 Daniele Panozzo <daniele.panozzo@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public License
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.
#include "write_image.h"
#include <stb_image_write.h>
#include <vector>
#include "../pathinfo.h"

IGL_INLINE bool igl::stb::write_image(
  const std::string image_file,
  const Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic>& R,
  const Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic>& G,
  const Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic>& B,
  const Eigen::Matrix<unsigned char,Eigen::Dynamic,Eigen::Dynamic>& A,
  const int quality
)
{
  assert((R.rows() == G.rows()) && (G.rows() == B.rows()) && (B.rows() == A.rows()));
  assert((R.cols() == G.cols()) && (G.cols() == B.cols()) && (B.cols() == A.cols()));

  const int comp = 4;                                  // 4 Channels Red, Green, Blue, Alpha
  std::vector<unsigned char> data(R.size()*comp,0);     // The image itself;

  for (unsigned i = 0; i<R.rows();++i)
  {
    for (unsigned j = 0; j < R.cols(); ++j)
    {
        data[(j * R.rows() * comp) + (i * comp) + 0] = R(i,R.cols()-1-j);
        data[(j * R.rows() * comp) + (i * comp) + 1] = G(i,R.cols()-1-j);
        data[(j * R.rows() * comp) + (i * comp) + 2] = B(i,R.cols()-1-j);
        data[(j * R.rows() * comp) + (i * comp) + 3] = A(i,R.cols()-1-j);
    }
  }
  return write_image(image_file,R.rows(),R.cols(),data.data(),quality);
}

IGL_INLINE bool igl::stb::write_image(
  const std::string image_file,
  const int width,
  const int height,
  const unsigned char * rgba_data,
  const int quality)
{
  const int comp = 4;                                  // 4 Channels Red, Green, Blue, Alpha
  const int stride_in_bytes = width*comp;           // Length of one row in bytes
  using namespace std;
  string d,b,e,f;
  pathinfo(image_file,d,b,e,f);
  if(e == "png")
  {
    return stbi_write_png(image_file.c_str(), width, height, comp, rgba_data, stride_in_bytes)!=0;
  } else if( e == "tga") 
  {
    return stbi_write_tga(image_file.c_str(), width, height, comp, rgba_data)!=0;
  } else if( e == "bmp") 
  {
    return stbi_write_bmp(image_file.c_str(), width, height, comp, rgba_data)!=0;
  } else if( e == "jpg") 
  {
    return stbi_write_jpg(image_file.c_str(), width, height, comp, rgba_data,quality)!=0;
  } else 
  {
    // unsupported file format
    return false;  
  }
  // not yet.
  //} else if( e == "hdr") 
  // {
  //  return stbi_write_hdr(image_file.c_str(), width, height, comp, rgba_data.rgba_data())!=0;
  // }
}

#ifdef IGL_STATIC_LIBRARY
// Explicit template instantiation
// generated by autoexplicit.sh
#endif
