//#include <stdio.h>
#include <physfs.h>
#include "Utility.h"


namespace corona {

  class CFile : public DLLImplementation<File> {
  public:
    CFile(PHYSFS_File* file) {
      m_file = file;
    }

    ~CFile() {
      PHYSFS_close(m_file);
    }

    int COR_CALL read(void* buffer, int size) {
      return (int)PHYSFS_read(m_file, buffer, 1, size );
    }

    int COR_CALL write(const void* buffer, int size) {
      return (int)PHYSFS_write(m_file, buffer, 1, size );
    }

    bool COR_CALL seek(int position, SeekMode mode) {
      PHYSFS_uint64 pos;
      switch (mode) {
        case BEGIN:   pos = position; break;
        case CURRENT: pos = PHYSFS_tell(m_file) + position; break;
        case END:     pos = PHYSFS_fileLength( m_file ) + position; break;
        default: return false;
      }
      return PHYSFS_seek(m_file, pos) != 0;
    }

    int COR_CALL tell() {
      return (int)PHYSFS_tell(m_file);
    }

  private:
    PHYSFS_File* m_file;
  };


  COR_EXPORT(File*) CorOpenFile(const char* filename, bool writeable) {
  	PHYSFS_File* file;
  	if( writeable )
    	file = PHYSFS_openWrite(filename);
    else
    	file = PHYSFS_openRead(filename);
    return (file ? new CFile(file) : 0);
  }

}
