#include "wrap-camera.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <utime.h>

WrapCamera::WrapCamera(WrapGphoto2 * init_wgp, Camera * init_camera)
 : wgp(init_wgp), camera(init_camera) {
   return;
}

WrapCamera::~WrapCamera() {
   gp_camera_free(camera);
   camera = NULL;
}

QStringList
WrapCamera::FilesInDirectory(QString dirname) {
   QStringList rval;
   CameraList * filelist;
   if (gp_list_new(&filelist) >= GP_OK) {
      if (gp_camera_folder_list_files(camera, dirname.toAscii().constData(),
                                      filelist, wgp->GetContext()) >= GP_OK) {
         int filecount = gp_list_count(filelist);
         for (int i = 0; i < filecount; ++i) {
            const char * name;
            if (gp_list_get_name(filelist, i, &name) >= GP_OK) {
               rval << QString(name);
            }
         }
      }
      gp_list_free(filelist);
   }
   return rval;
}

bool
WrapCamera::FetchFile(
   QString srcdir,
   QString srcfile,
   QString destdir,
   QString destfile) {

   int fd;
   CameraFile *file;
   bool rval = false;
   QString fulldest(destdir);
   fulldest.append("/");
   fulldest.append(destfile);
   fd = open(fulldest.toAscii().constData(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
   if (fd >= 0) {
      if (gp_file_new_from_fd(&file, fd) >= GP_OK) {
         if (gp_camera_file_get(camera,
                                srcdir.toAscii().constData(),
                                srcfile.toAscii().constData(),
                                GP_FILE_TYPE_NORMAL,
                                file,
                                wgp->GetContext()) >= GP_OK) {
            time_t mtime;
            bool run_utime = (gp_file_get_mtime(file, &mtime) >= GP_OK);
            gp_file_unref(file);
            close(fd);
            if (run_utime) {
               struct utimbuf u;
               memset((void *)&u, 0, sizeof(u));
               u.actime = mtime;
               u.modtime = mtime;
               utime(fulldest.toAscii().constData(), &u);
            }
            rval = true;
         }
      }
   }
   return rval;
}

bool
WrapCamera::DeleteFile(QString srcdir, QString srcfile) {
   if (gp_camera_file_delete(camera,
                             srcdir.toAscii().constData(),
                             srcfile.toAscii().constData(),
                             wgp->GetContext()) >= GP_OK) {
      return true;
   }
   return false;
}
