#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# sets the nick-name of Empathy in file $HOME/.mission-control/accounts/accounts.cfg
# requires python-gtk2, Empathy 
# Uses configuration file in $HOME/.config/empathy-salut-nickname
#
# Author: gaurav <gau1991@gmail.com>
# Revision: JM. Philippe <jean-michel.philippe@doudoulinux.org>
#
# This file is part of DoudouLinux.
#
# DoudouLinux 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 3 of the License, or
# (at your option) any later version.
#
# DoudouLinux 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 DoudouLinux.  If not, see <http://www.gnu.org/licenses/>.

############
# NB: we need gtk only if a GUI is required
import pygtk
import gtk
import commands
import os
import sys
import gettext, subprocess
import shutil

############
# i18n and image folder
ScriptDir = os.path.dirname(sys.argv[0])
if ScriptDir == "/usr/bin":
	gettext.install(domain='empathy-salut-nickname', unicode=True)
	ImageDir = "/usr/share/empathy-salut-nickname/icons"
	ConfTemplate = "/usr/share/empathy-salut-nickname/accounts.cfg"
else:
	# we may be testing without having installed the Debian package
	# in this case MO files should be placed in a hidden .locale/ directory
	# use the script “po2mo.sh” to do so.
	gettext.install(
		domain="empathy-salut-nickname",
		unicode=True,
		localedir=os.path.join(ScriptDir, "..", ".locale"),
	)
	ImageDir = os.path.join(ScriptDir, "..", "data", "icons")
	ConfTemplate = os.path.join(ScriptDir, "..", "data", "accounts.cfg")

############
# constants
EmpathySalut = ".mission-control/accounts/accounts.cfg"
AppsImage = os.path.join(ImageDir, "user-talk.svg")
ConfigFilePath = "$HOME/.config/empathy-salut-nickname"

################
###Variables
#IsEmapthy is for to check Eapathy is running or not
IsEmpathy = commands.getstatusoutput("ps -A | grep empathy ")
###StartInfoBox is for to start Start Info box or not
StartInfoBox = 1
####EmpathyPid return PID of running Empathy
EmpathyPid = "0"
####SetOnly returns command line argument option entered by user
SetOnly = False
########RunEmpathy is used to strat empathy or not
RunEmpathy = 1
####
flag = 1

if IsEmpathy[0]==0:
	StartInfoBox = 0
	tmp = IsEmpathy[1].split()
	EmpathyPid = tmp[0]

###########

###########
# scan input args
if len(sys.argv)>1:
	if sys.argv[1] in ["-s", "--set-only"]:
		SetOnly = True
	elif sys.argv[1] in ["-h", "--help"]:
		print """Sets the user's nickname of the Empathy salut account

Usage:
  $ empathy-salut-nickname [-h|--help] [-s|--set-only]

Option -s or --set-only don't start Empathy after clicking OK.
Default is to start Empathy.
"""
		sys.exit()
	else:
		print "ERROR: unkown input argument(s)", ', '.join(sys.argv[1:])
		print "To get help: empathy-salut-nickname -h"
		sys.exit()

print SetOnly
#IsConfig reads the value from configuartion file
#starts apps if it is 0
IsConfig=(1, '0')
if not SetOnly:
	IsConfig = commands.getstatusoutput("cat " + ConfigFilePath)
	if IsConfig[0]!=0:
		commands.getstatusoutput("echo 0 > " + ConfigFilePath)
		IsConfig=(1, '0')

class ChangeUser:
	#IsNext is used to start on next time or not if 0 then start
	IsNext = 0
	#RunEmpathy is used to start Empathy or not
	RunEmpathy = 0

	############
	#StartEmpathy changes the nick name in configuration file of Empathy and starts Empathy
	def startempathy(self, widget, entry, data = None):
		self.ChUsrName(widget, entry, data=data)
		self.RunEmpathy = 1

	############
	#ChUsrName changes the nick name in configuration file of Empathy but not start empathy
	def ChUsrName(self, widget, entry, data = None):
		UsrName = entry.get_text()
		ConfFile = os.path.join(os.environ['HOME'], EmpathySalut)
		if not os.path.isfile(ConfFile):
			shutil.copyfile(ConfTemplate, ConfFile)
		
		SedOp = commands.getstatusoutput(
			"sed -ri 's/^(N|param-n)ickname=.*$/\\1ickname=%s/' %s" % (UsrName, ConfFile)
		)
		if SedOp[0]==0:
			print _("Success")
		else:
			print _("Failed")
		if self.IsNext==1:
			commands.getstatusoutput("echo 1 > " + ConfigFilePath)


	###############
	#delet_event and destroy are used to close the application
	def delet_event(self, widget, event, data = None):
		gtk.main_quit()
		return False

	###############
	def destroy(self, widget, data = None):
		gtk.main_quit()

	###############
	#callback changes the value is_next from checkbox
	def callback(self, widget, data = None):
		if self.IsNext==0:
			self.IsNext = 1
		elif self.IsNext==1:
			self.IsNext = 0

	def CancelWin(self, widget, data = None):
		self.RunEmpathy = 0		
		gtk.main_quit()

	################
	def __init__(self):
		
		############################################
		##GUI functions for changing nickname Window
		############################################
		self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
		self.window.connect("destroy", self.destroy)
		self.window.set_title(_("Nickname on the network"))	
		table = gtk.Table(19, 14, False)
		self.window.add(table)

		#############################
		event_box = gtk.EventBox()
		table.attach(event_box, 0, 14, 0, 9)
		event_box.show()

		###############
		table2 = gtk.Table(8, 5, True)
		event_box.add(table2)
		event_box.modify_bg(gtk.STATE_NORMAL, event_box.get_colormap().alloc_color("#d5daf1"))

		#Addition Of Image
		image = gtk.Image()
		image.set_from_file(AppsImage)
		table2.attach(image, 0, 5, 0, 8, gtk.FILL, gtk.FILL, 5, 5)
		image.show()

		######################
		label1 = gtk.Label(_("""With Empathy you can talk to
your neighbors connected to the
local network. DoudouLinux has
configured it to make it unable
to reach people on the Internet."""))
		table2.attach(label1, 5, 14, 0, 8, gtk.FILL, gtk.FILL, 10, 5)
		label1.show()
		
		table2.show()

		#################
		label2 = gtk.Label(_("""Choose your name
on the network"""))
		table.attach(label2, 1, 7, 10, 14, gtk.FILL, gtk.FILL, 5, 5)
		label2.show()
		
		################
		entry = gtk.Entry()
		Result = commands.getoutput(
			"grep -i nickname %s" % os.path.join(os.environ['HOME'], EmpathySalut)
		)
		Result = [x.split("=")[1] for x in Result.split()]
		if len(Result[0]) > len(Result[1]):
			entry.set_text(Result[0])
		else:
			entry.set_text(Result[1])
		table.attach(entry, 8, 13, 10, 13, gtk.FILL, gtk.FILL, 5, 5)
		entry.show()

		################
		if not SetOnly:
			cbutton = gtk.CheckButton(_("Don't ask next time"))
			cbutton.connect("toggled", self.callback)
			table.attach(cbutton, 7, 13, 13, 15)
			cbutton.show()

		################
		#ok button, calls ChUsrName
		if SetOnly:
			button = gtk.Button(None,"gtk-apply")
			button.connect("clicked", self.ChUsrName, entry, None)
			button.connect_object("clicked", gtk.Widget.destroy, self.window)
			table.attach(button, 1, 4, 16, 18, gtk.FILL, gtk.FILL, 5, 5)
			button.show()
		
		##################
		button2 = gtk.Button(_("Apply & Start Empathy"))
		button2.connect("clicked", self.startempathy, entry, None)
		button2.connect_object("clicked", gtk.Widget.destroy, self.window)
		table.attach(button2, 9, 12, 16, 18, gtk.FILL, gtk.FILL, 5, 5)
		button2.show()

		###################
		button1 = gtk.Button(None,"gtk-close")
		button1.connect("clicked", self.CancelWin, None)
		table.attach(button1, 5, 8, 16, 18, gtk.FILL, gtk.FILL, 10, 5)
		button1.show()

		table.show()

		self.window.show()
		self.window.set_resizable(False)
	
	#############
	def main(self):
		gtk.main()
		return self.RunEmpathy
		
class infobox:
	###IsGui is used to start ChUsr Gui or not
	IsGui = 0
	#############
	def delet_event(self, widget, event, data = None):
		gtk.main_quit()
		return False

	###############
	def destroy(self, widget, data = None):
		gtk.main_quit()

	###############
	def setnext(self, widget, data = None):
		self.IsGui = 1


	############################################
	##GUI functions for info Window
	############################################
	def __init__(self):
		self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
		self.window.connect("destroy", self.destroy)
		self.window.set_title(_("Empathy is running"))
		table = gtk.Table(5, 5, False)
		self.window.add(table)

		###################
		stock = gtk.Image()
		stock.set_from_stock(gtk.STOCK_DIALOG_WARNING, size = gtk.ICON_SIZE_DIALOG)
		table.attach(stock, 0, 4, 0, 2, gtk.FILL, gtk.FILL, 5, 5)
		stock.show()
		
		########################
		label = gtk.Label(_("""Empathy is already running. If you
change your nickname, this will not 
have effect until you restart Empathy."""))
		table.attach(label, 4, 5, 0, 2, gtk.FILL, gtk.FILL, 5, 5)
		label.show()

		#####################
		button = gtk.Button(None,"gtk-ok")
		button.connect("clicked", self.setnext, None)
		button.connect_object("clicked", gtk.Widget.destroy, self.window)
		table.attach(button, 3, 5, 4, 5, gtk.FILL, gtk.FILL, 5, 5)
		button.show()
		
		####################
		button1 = gtk.Button(None,"gtk-cancel")
		button1.connect("clicked", self.destroy, None)
		table.attach(button1, 0, 3, 4, 5, gtk.FILL, gtk.FILL, 5, 5)
		button1.show()

		table.show()

		self.window.show()
		self.window.set_resizable(False)

	####################
	def main(self):
		gtk.main()
		return self.IsGui


if StartInfoBox==0:
	if IsConfig[1]=='0' or SetOnly:
		chwin = infobox()
		StartInfoBox = chwin.main()
		flag = StartInfoBox


if IsConfig[1]=='0' or SetOnly:
	if StartInfoBox==1:
		usr = ChangeUser()
		RunEmpathy = usr.main()

if RunEmpathy==1 and flag==1:
		#if EmpathyPid!="0":
			#commands.getstatusoutput("kill "+ EmpathyPid)
			#print "Killed"
		subprocess.Popen("empathy")
		#print "runs"

exit(0)
