def menu_preferences_response(self,widget):
		widget.set_sensitive(False)
		p = Preferences(self.tasks)
		if p.run() == Gtk.ResponseType.ACCEPT:
			p.save_preferences()
		p.destroy()
		self.read_preferences()
		self.menu_update()
		widget.set_sensitive(True)
	def menu_preferences_response(self,widget):
		self.set_menu_sensitive(False)
		p1 = Preferences(self.googlecalendar)
		if p1.run() == Gtk.ResponseType.ACCEPT:
			p1.save_preferences()			
			if not os.path.exists(comun.TOKEN_FILE) or self.googlecalendar.do_refresh_authorization() is None:
				exit(-1)
			self.load_preferences()
			self.events = []	
			self.update_menu()		
		p1.destroy()
		self.set_menu_sensitive(True)
    def __init__(self):
        if dbus.SessionBus().request_name(
                "es.atareao.calendar-indicator"
        ) != dbus.bus.REQUEST_NAME_REPLY_PRIMARY_OWNER:
            print("application already running")
            exit(0)
        self.indicator = appindicator.Indicator.new(
            'Calendar-Indicator', 'Calendar-Indicator',
            appindicator.IndicatorCategory.APPLICATION_STATUS)
        self.notification = Notify.Notification.new('', '', None)
        self.googlecalendar = GoogleCalendar(token_file=comun.TOKEN_FILE)
        error = True
        while (error):
            if self.googlecalendar.do_refresh_authorization() is None:
                p = Preferences()
                if p.run() == Gtk.ResponseType.ACCEPT:
                    p.save_preferences()
                p.destroy()
                self.googlecalendar = GoogleCalendar(
                    token_file=comun.TOKEN_FILE)
                if (not os.path.exists(comun.TOKEN_FILE)) or (
                        self.googlecalendar.do_refresh_authorization() is
                        None):
                    md = Gtk.MessageDialog(
                        parent=None,
                        flags=Gtk.DialogFlags.MODAL
                        | Gtk.DialogFlags.DESTROY_WITH_PARENT,
                        type=Gtk.MessageType.ERROR,
                        buttons=Gtk.ButtonsType.OK_CANCEL,
                        message_format=
                        _('You have to authorize Calendar-Indicator to manage your Google Calendar.\n Do you want to authorize?'
                          ))
                    if md.run() == Gtk.ResponseType.CANCEL:
                        exit(3)
                    md.destroy()
                else:
                    self.googlecalendar = GoogleCalendar(
                        token_file=comun.TOKEN_FILE)
                    if self.googlecalendar.do_refresh_authorization() is None:
                        error = False
            else:
                error = False
        self.load_preferences()

        self.load_css()

        self.events = []
        self.create_menu()
        self.sync()
        self.update_menu()
        self.actualization_time = time.time()
        GLib.timeout_add_seconds(60, self.work)
	def menu_preferences_response(self,widget):
		widget.set_sensitive(False)
		p = Preferences(self.tasks)
		if p.run() == Gtk.ResponseType.ACCEPT:
			p.save_preferences()
		p.destroy()
		self.read_preferences()
		self.menu_update()
		widget.set_sensitive(True)
	def menu_preferences_response(self,widget):
		self.set_menu_sensitive(False)
		p1 = Preferences(self.googlecalendar)
		if p1.run() == Gtk.ResponseType.ACCEPT:
			p1.save_preferences()			
			if not os.path.exists(comun.TOKEN_FILE) or self.googlecalendar.do_refresh_authorization() is None:
				exit(-1)
			self.load_preferences()
			self.events = []	
			self.update_menu()		
		p1.destroy()
		self.set_menu_sensitive(True)
	def read_preferences(self):
		error = True
		while error:
			try:
				configuration = Configuration()
				self.tasklist_id = configuration.get('tasklist_id')
				self.theme = configuration.get('theme')
				error = False
			except Exception as e:
				print(e)
				error = True
				p = Preferences()
				if p.run() == Gtk.ResponseType.ACCEPT:
					p.save_preferences()
				else:
					exit(1)
				p.destroy()
	def __init__(self):
		if dbus.SessionBus().request_name("es.atareao.calendar-indicator") != dbus.bus.REQUEST_NAME_REPLY_PRIMARY_OWNER:
			print("application already running")
			exit(0)
		self.indicator = appindicator.Indicator.new('Calendar-Indicator', 'Calendar-Indicator', appindicator.IndicatorCategory.APPLICATION_STATUS)
		self.notification = Notify.Notification.new('','', None)
		self.googlecalendar = GoogleCalendar(token_file = comun.TOKEN_FILE)
		error = True
		while(error):
			if self.googlecalendar.do_refresh_authorization() is None:
				p = Preferences()
				if p.run() == Gtk.ResponseType.ACCEPT:
					p.save_preferences()
				p.destroy()
				self.googlecalendar = GoogleCalendar(token_file = comun.TOKEN_FILE)
				if (not os.path.exists(comun.TOKEN_FILE)) or (self.googlecalendar.do_refresh_authorization() is None):
					md = Gtk.MessageDialog(	parent = None,
											flags = Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT,
											type = Gtk.MessageType.ERROR,
											buttons = Gtk.ButtonsType.OK_CANCEL,
											message_format = _('You have to authorize Calendar-Indicator to manage your Google Calendar.\n Do you want to authorize?'))
					if md.run() == Gtk.ResponseType.CANCEL:
						exit(3)
					md.destroy()
				else:
					self.googlecalendar = GoogleCalendar(token_file = comun.TOKEN_FILE)
					if self.googlecalendar.do_refresh_authorization() is None:
						error = False
			else:
				error = False
		self.load_preferences()
		#
		self.events = []
		self.create_menu()
		self.sync()
		self.update_menu()
		self.actualization_time = time.time()
		GLib.timeout_add_seconds(60, self.work)
	def sync(self,widget):
		gta = googletasksapi.GTAService(token_file = comun.TOKEN_FILE)
		error = True
		while(error):
			if gta.do_refresh_authorization() is None:
				p = Preferences(self.tasks)
				if p.run() == Gtk.ResponseType.ACCEPT:
					p.save_preferences()
				p.destroy()
				gta = googletasksapi.GTAService(token_file = comun.TOKEN_FILE)
				if (not os.path.exists(comun.TOKEN_FILE)) or (gta.do_refresh_authorization() is None):
					md = Gtk.MessageDialog(	parent = None,
											flags = Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT,
											type = Gtk.MessageType.ERROR,
											buttons = Gtk.ButtonsType.OK_CANCEL,
											message_format = _('You have to authorize Google-Tasks-Indicator to manage your Google Calendar.\n Do you want to authorize?'))
					if md.run() == Gtk.ResponseType.CANCEL:
						md.destroy()
						return
					md.destroy()
				else:
					gta = googletasksapi.GTAService(token_file = comun.TOKEN_FILE)
					if gta.do_refresh_authorization() is None:
						error = False
			else:
				error = False
		## Options
		configuration = Configuration()
		option_local = configuration.get('local')
		option_external = configuration.get('external')
		option_both = configuration.get('both')
		##
		google_tasklists = gta.get_tasklists()
		
		## From Local to Google ##
		google_task_lists_ids = []
		for gtl in google_tasklists.values():
			google_task_lists_ids.append(gtl['id'])			
		for tasklist in self.tasks.tasklists.values():
			if tasklist['id'] not in google_task_lists_ids: # Tasklist only local
				if option_local == 0: # Copy to external
					new_tasklist = gta.create_tasklist(tasklist['title'])
					if new_tasklist is not None:
						for task in tasklist['tasks'].values():
							if 'due' in task.keys() and task['due'] is not None:
								due = rfc3339.parse_datetime(str(task['due']))
							else:
								due = None
							new_task = gta.create_task( tasklist_id = new_tasklist['id'], title = task['title'], notes=task['notes'], iscompleted=task.get_completed(),due=due,data_completed=task['completed'])
							new_tasklist['tasks'][new_task['id']] = new_task
						self.tasks.remove_tasklist(tasklist)
						self.tasks.tasklists[new_tasklist['id']] = new_tasklist
				elif option_local == 1: # delete local
					self.tasks.remove_tasklist(tasklist)
			else: # Tasklist local and external;
				if option_both == 0: # Copy to local
					gtl = google_tasklists[tasklist['id']]
					tasklist['title'] = gtl['title']
				elif option_both == 1: # Copy to external
					if gtl['title'] != tasklist['title']:
						gta.edit_tasklist(tasklist['id'],tasklist['title'])
				########################################################
				## Working with tasks
				localtasks = tasklist['tasks']
				googletasks = gta.get_tasks(tasklist_id=tasklist['id'])
				### From Local to Google
				for task in localtasks.values():
					if task['id'] not in googletasks.keys():
						# Task only local
						if option_local == 0:
							# Copy to external
							new_task = gta.create_task( tasklist_id = task['tasklist_id'], title = task['title'], notes=task['notes'], iscompleted=task.get_completed(),due=task['due'],data_completed=task['completed'])
							if new_task is not None:
								self.tasks.remove_task(task)
								self.tasks.tasklists[task['tasklist_id']]['tasks'][new_task['id']] = new_task
						elif option_local == 1:
							# Delete local
							self.tasks.remove_task(task)
					else:
						#Task local and external
						if option_both == 0:
							# Copy to local
							self.tasks.tasklists[task['tasklist_id']]['tasks'][task['id']] = googletasks[task['id']]
						elif option_both ==1:
							# Copy to external
							task_id = task['id']
							tasklist_id = task['tasklist_id']
							title = task['title']
							notes = task['notes']
							iscompleted = (task['status']=='completed')
							due = task['due']
							gta.edit_task(task_id, tasklist_id , title = title, notes = notes, iscompleted = iscompleted, due = due)
				### From Google to Local
				for task in googletasks.values():
					if task['id'] not in localtasks.keys():
						#Task only external
						if option_external == 0:
							# Copy to local
							self.tasks.tasklists[task['tasklist_id']]['tasks'][task['id']] = googletasks[task['id']]
						elif option_external == 1:
							# Delete external
							gta.delete_task(task['id'], task['tasklist_id'])
				########################################################
		## From Google to Local ##
		alone_task_lists_ids = []
		for atl in self.tasks.tasklists.values():
			alone_task_lists_ids.append(atl['id'])			
		for tasklist in google_tasklists.values():
			if tasklist['id'] not in alone_task_lists_ids: # Tasklist only Google
				if option_external == 0: # Copy to local
					new_tasklist = tasklist
					new_tasklist['tasks'] = gta.get_tasks(tasklist_id = tasklist['id'])
					self.tasks.tasklists[new_tasklist['id']] = new_tasklist	
				elif option_external == 1: # Delete external
					gta.delete_tasklist(tasklist)
		self.tasks.backup()
		self.menu_update()
	def sync(self,widget):
		gta = googletasksapi.GTAService(token_file = comun.TOKEN_FILE)
		error = True
		while(error):
			if gta.do_refresh_authorization() is None:
				p = Preferences(self.tasks)
				if p.run() == Gtk.ResponseType.ACCEPT:
					p.save_preferences()
				p.destroy()
				gta = googletasksapi.GTAService(token_file = comun.TOKEN_FILE)
				if (not os.path.exists(comun.TOKEN_FILE)) or (gta.do_refresh_authorization() is None):
					md = Gtk.MessageDialog(	parent = None,
											flags = Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT,
											type = Gtk.MessageType.ERROR,
											buttons = Gtk.ButtonsType.OK_CANCEL,
											message_format = _('You have to authorize Google-Tasks-Indicator to manage your Google Calendar.\n Do you want to authorize?'))
					if md.run() == Gtk.ResponseType.CANCEL:
						md.destroy()
						return
					md.destroy()
				else:
					gta = googletasksapi.GTAService(token_file = comun.TOKEN_FILE)
					if gta.do_refresh_authorization() is None:
						error = False
			else:
				error = False
		## Options
		configuration = Configuration()
		option_local = configuration.get('local')
		option_external = configuration.get('external')
		option_both = configuration.get('both')
		##
		google_tasklists = gta.get_tasklists()
		
		## From Local to Google ##
		google_task_lists_ids = []
		for gtl in google_tasklists.values():
			google_task_lists_ids.append(gtl['id'])			
		for tasklist in self.tasks.tasklists.values():
			if tasklist['id'] not in google_task_lists_ids: # Tasklist only local
				if option_local == 0: # Copy to external
					new_tasklist = gta.create_tasklist(tasklist['title'])
					if new_tasklist is not None:
						for task in tasklist['tasks'].values():
							if 'due' in task.keys() and task['due'] is not None:
								due = rfc3339.parse_datetime(str(task['due']))
							else:
								due = None
							new_task = gta.create_task( tasklist_id = new_tasklist['id'], title = task['title'], notes=task['notes'], iscompleted=task.get_completed(),due=due,data_completed=task['completed'])
							new_tasklist['tasks'][new_task['id']] = new_task
						self.tasks.remove_tasklist(tasklist)
						self.tasks.tasklists[new_tasklist['id']] = new_tasklist
				elif option_local == 1: # delete local
					self.tasks.remove_tasklist(tasklist)
			else: # Tasklist local and external;
				if option_both == 0: # Copy to local
					gtl = google_tasklists[tasklist['id']]
					tasklist['title'] = gtl['title']
				elif option_both == 1: # Copy to external
					if gtl['title'] != tasklist['title']:
						gta.edit_tasklist(tasklist['id'],tasklist['title'])
				########################################################
				## Working with tasks
				localtasks = tasklist['tasks']
				googletasks = gta.get_tasks(tasklist_id=tasklist['id'])
				### From Local to Google
				print(localtasks)
				for task in localtasks.values():
					if task['id'] not in googletasks.keys():
						# Task only local
						if option_local == 0:
							# Copy to external
							new_task = gta.create_task( tasklist_id = task['tasklist_id'], title = task['title'], notes=task['notes'], iscompleted=task.get_completed(),due=task['due'],data_completed=task['completed'])
							if new_task is not None:
								self.tasks.remove_task(task)
								self.tasks.tasklists[task['tasklist_id']]['tasks'][new_task['id']] = new_task
						elif option_local == 1:
							# Delete local
							self.tasks.remove_task(task)
					else:
						#Task local and external
						if option_both == 0:
							# Copy to local
							self.tasks.tasklists[task['tasklist_id']]['tasks'][task['id']] = googletasks[task['id']]
						elif option_both ==1:
							# Copy to external
							task_id = task['id']
							tasklist_id = task['tasklist_id']
							title = task['title']
							notes = task['notes']
							iscompleted = (task['status']=='completed')
							due = task['due']
							gta.edit_task(task_id, tasklist_id , title = title, notes = notes, iscompleted = iscompleted, due = due)
				### From Google to Local
				for task in googletasks.values():
					if task['id'] not in localtasks.keys():
						#Task only external
						if option_external == 0:
							# Copy to local
							self.tasks.tasklists[task['tasklist_id']]['tasks'][task['id']] = googletasks[task['id']]
						elif option_external == 1:
							# Delete external
							gta.delete_task(task['id'], task['tasklist_id'])
				########################################################
		## From Google to Local ##
		alone_task_lists_ids = []
		for atl in self.tasks.tasklists.values():
			alone_task_lists_ids.append(atl['id'])			
		for tasklist in google_tasklists.values():
			if tasklist['id'] not in alone_task_lists_ids: # Tasklist only Google
				if option_external == 0: # Copy to local
					new_tasklist = tasklist
					new_tasklist['tasks'] = gta.get_tasks(tasklist_id = tasklist['id'])
					self.tasks.tasklists[new_tasklist['id']] = new_tasklist	
				elif option_external == 1: # Delete external
					gta.delete_tasklist(tasklist)
		self.tasks.backup()
		self.menu_update()