#!/usr/bin/env python

# Copyright 2009 Jay Reding

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 	http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

try:
  from xml.etree import ElementTree # for Python 2.5 users
except:
  from elementtree import ElementTree

import os
import base64
import time
import string

import gtk
import gtk.glade
import gnome.ui
import gobject

import feedparser

import gdata
import atom

# Internal Libraries
import config
import editor
import firstrun

class FileHandler():

	def __init__(self):
	
		return None	

	def main(self):
	
		return True

	def saveFile(self, postStruct, parentWin):

		# Our first task is to create an XML file with our post data

		postAsXML = self.postStructToXML(postStruct)

		# Now, we need to create our dialog for saving our file.
		saveFileDialog = gtk.FileChooserDialog('Save File', parentWin, gtk.FILE_CHOOSER_ACTION_SAVE)

		# We need to establish some file filters to help users narrow their choices
		saveFilter = gtk.FileFilter()
		saveFilter.add_pattern('*.blogtk')
		saveFilter.set_name('BloGTK Saved Posts')

		allFilter = gtk.FileFilter()
		allFilter.add_pattern('*')
		allFilter.set_name('All Files')

		saveFileDialog.add_filter(saveFilter)
		saveFileDialog.add_filter(allFilter)

		# Set our defaults for the save dialog
		saveFileDialog.set_do_overwrite_confirmation(True)
		saveFileDialog.add_buttons(gtk.STOCK_SAVE, gtk.RESPONSE_ACCEPT, gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT)
		saveFileDialog.set_current_name('.blogtk')

		response = saveFileDialog.run()

		if response == gtk.RESPONSE_ACCEPT:
			filename = saveFileDialog.get_filename()

			try:
				saveFile = open(filename, "w")
				saveFile.write(postAsXML)
				saveFile.close()
			except Exception, e:
				saveFileDialog.destroy()
				return False, str(e)
			
			saveFileDialog.destroy()

			return True, filename
		else:
			saveFileDialog.destroy()

			return False, 'cancel'

	def resaveFile(self, postStruct, filename):

		postAsXML = self.postStructToXML(postStruct)

		try:
			saveFile = open(filename, "w")
			saveFile.write(postAsXML)
			saveFile.close()
		except Exception, e:
			return False, str(e)

		return True, filename

	def openFile(self, parentWin):
		# Now, we need to create our dialog for loading our file.
		openFileDialog = gtk.FileChooserDialog('Open File', parentWin, gtk.FILE_CHOOSER_ACTION_OPEN)

		# We need to establish some file filters to help users narrow their choices
		openFilter = gtk.FileFilter()
		openFilter.add_pattern('*.blogtk')
		openFilter.set_name('BloGTK Saved Posts')