//  BMP
//  Copyright (C) 2005 BMP development.
//
//  This program is free software; you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation; either version 2 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
//  --
//
//  The BMPx project hereby grants permission for non-GPL compatible GStreamer
//  plugins to be used and distributed together with GStreamer and BMPx. This
//  permission is above and beyond the permissions granted by the GPL license
//  BMPx is covered by.

#include <boost/format.hpp>

#include <glibmm.h>
#include <glibmm/i18n.h>
#include <iostream>
#include <fstream>
#include <istream>

#include <src/vfs.hh>
#include <src/uri.hh>

namespace Bmp
{
  namespace VFS
  {
      class PluginTransportFile
        : public Bmp::VFS::PluginTransportBase
      {

        public:

          virtual bool	
          can_process (const Glib::ustring& uri)
          {
              Bmp::URI u (uri);
              return (u.get_protocol () == Bmp::URI::PROTOCOL_FILE);
          }

          virtual void
          handle_read (Bmp::VFS::Handle& handle) throw (ProcessingError)
          {
            std::string filename; 
            try{
                filename = Glib::filename_from_uri (handle.get_uri ());
              }
            catch (...)
              {
                throw ProcessingError ((boost::format (_("Unable to create a filename from '%s'")) % handle.get_uri()).str());
              }
            std::string str = Glib::file_get_contents (filename);
            handle.set_buffer (reinterpret_cast<const unsigned char*>(str.data()), str.length()+1); 
          }

          virtual void
          handle_write (const Bmp::VFS::Handle& handle) throw (ProcessingError)
          {
            std::string filename; 

            try{
                filename = Glib::filename_from_uri (handle.get_uri ());
              }
            catch (...)
              {
                throw ProcessingError ((boost::format (_("Unable to write to %s")) % handle.get_uri()).str());
              }

            std::ofstream outfile;
            outfile.open (filename.c_str(), std::ios::binary);
            outfile << handle.get_buffer ();
            outfile.close ();
          }
      };
    }
}
  
extern "C" Bmp::VFS::PluginTransportBase* plugin_create ()
{
  return new Bmp::VFS::PluginTransportFile;
}

extern "C" void plugin_delete (Bmp::VFS::PluginTransportFile* p)
{
  delete p;
}
