#include <storage/AppFileInfo.h>
#include <storage/Path.h>
#include <storage/File.h>
#include <storage/FindDirectory.h>

#include "ShareApplication.h"

namespace beshare {

#define BESHARE_SETTINGS_FILE_NAME "beshare_settings"   

ShareApplication :: ShareApplication(const char * optConnectTo) : BApplication(BESHARE_MIME_TYPE), _window(NULL), _optConnectTo(optConnectTo)
{
   // Get default settings path
   BPath sPath;
   if (find_directory(B_USER_SETTINGS_DIRECTORY, &sPath) == B_NO_ERROR)
   {
      sPath.Append(BESHARE_SETTINGS_FILE_NAME);
      _settingsFileEntry.SetTo(sPath.Path());
   }
}

ShareApplication :: ~ShareApplication()
{
   // empty
}

void ShareApplication :: SaveSettings(const BMessage & settings)
{
   BFile settingsFile(&_settingsFileEntry, B_WRITE_ONLY|B_CREATE_FILE|B_ERASE_FILE);
   if (settingsFile.InitCheck() == B_NO_ERROR) 
   {
      (void) settings.Flatten(&settingsFile);
      BAppFileInfo afi(&settingsFile);
      afi.SetType(BESHARE_MIME_TYPE);
   }
}

void ShareApplication :: RefsReceived(BMessage * msg)
{
   entry_ref ref; 
   if (msg->FindRef("refs", &ref) == B_NO_ERROR) _settingsFileEntry.SetTo(&ref);
}
  
void ShareApplication :: ReadyToRun()
{
   // Attempt to load settings...
   BFile settingsFile(&_settingsFileEntry, B_READ_ONLY);
   BMessage settings;
   if (settingsFile.InitCheck() == B_NO_ERROR) (void) settings.Unflatten(&settingsFile);
   _window = new ShareWindow(settings, _optConnectTo);
   _window->Show();
}

void ShareApplication :: DispatchMessage(BMessage * msg, BHandler * handler)
{
   if (msg->what == B_QUIT_REQUESTED)
   {
      if (msg->IsSourceRemote())
      {
         // Tell our window not to put up an 'are you sure' requester
         if ((_window)&&(_window->Lock()))
         {
            _window->SetEnableQuitRequester(false);
            _window->Unlock();
         }
      }
   }
   BApplication::DispatchMessage(msg, handler);
}

};  // end namespace beshare
