#!/usr/bin/env python3
#v2 09/14/2018
################################################
# 2016-2018 by Paul Sherman <psherman2001@gmail.com> 
#									        
# 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 3		
# 										
# 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.   
################################################
import tkinter.filedialog as filedialog
from tkinter import *
import tkinter.messagebox
import os, imghdr, re, subprocess, base64
from PIL import ImageTk, Image

APP_ICON = """
R0lGODlhMAAwAIQaAAAAAAAzAAAzMzMzMzMzZgBmMzNmZjNmmWZmZmZmmTOZZjOZmWaZmWaZzJmZ
mWbMzGbM/5nMzJnM/8zMmczMzMzM/8z/mcz/////Zv//mf///////////////////////yH5BAEK
AB8ALAAAAAAwADAAAAX+oCaOZGmeaKqup8O+MIoMVNwieK7vOUkBAISN5AAaj0hkbTQwuobNgWFq
4OUS2ISkwr0wjkIbECEpm8/otASCpMXG6ni8iQyz4PK8+Zt0r4AGeoISSU5/AIFnFhgZFINldIV2
J4BnGJeXE48HhUZ+JpVlFJiYEYMNnUdPJaESi6QYjmkNBgQCtwKpYKCIZq+ksmacusSTGq2jsGiR
xLqfra6kpmbMzc4j0BIRExPTZQTW4UvHvXoJ4dbj5Il56M3q63rD7p2r2AAEern0hfb3+XJQFRJA
wECCA+B0JUABBGCceUYINEijKxBDfHn2GWGgRmAhgBcdzjoyYKIaiEf+HIaUM29AnmoNz6ycA0SA
no9oZqZhA8RkHI8R0+hEcw4AxzxFjbCTSQmjmibsICxQY+DI0jPwRMTcCcCmmQUFpi4zokVNBGNa
nRIF4BNCgbdHzRjxiQaCALTkRJqZcgbs2wIQzLARQBdNVbxbDaP5+1aBmQZ60xxuGlnCg76M317O
s1nCZF4OFxQuk7mxngKbwSF2+uBtYMylw5rpXAasYwmqKZdR0Pg16di9edP+OzE3aAkMMpv0C5zx
bQnMC+AOQtltbN7NS09tzXiBcVb4sGcf//eB+L9NVg8gzz57rtUB2ssvPeYETH7o/In4gZ/fABUO
BCjggAQWaOCB+g0FoWAMIQAAOw=="""

top = Tk()

icondata= base64.b64decode(APP_ICON)
tempFile= "/tmp/icon.gif"
iconfile= open(tempFile,"wb")
iconfile.write(icondata)
iconfile.close()
try:
	img = PhotoImage(file='/tmp/icon.gif')
	top.tk.call('wm', 'iconphoto', top._w, img)
except:
	pass
os.remove(tempFile)
		
# this section bails from program if something is amiss ---------------------------------------------
# first, we check if the cwebp program is present:
f = subprocess.getoutput('type -path cwebp')
if not f:
	top.withdraw()
	tkinter.messagebox.showinfo("Error", "libwebp needs to be installed to use this utility")
	sys.exit(0)

# if we are not passed a filename, pop up a file open dialog
if len(sys.argv) < 2:
	file_name = filedialog.askopenfilename(title='Select a PNG file', filetypes=[('PNG files', '.png')])
	if not file_name:	
		sys.exit(0)
else:
	file_name = sys.argv[1]

# if the file name passed does not exist
if not os.path.isfile(file_name):
	top.withdraw()
	tkinter.messagebox.showinfo("Error", "This script is meant to be passed a PNG file")
	sys.exit(0)
		
# if the filename passed is not a png
x = imghdr.what(file_name)
if not x == 'png': 
  top.withdraw()
  tkinter.messagebox.showinfo("Error", "file_name does not appear to be a valid PNG image")
  sys.exit(0)

#----------------------------------------------------------------------------------------------------------------

pattern = re.compile(".png", re.IGNORECASE)
newname = pattern.sub(".webp", file_name)
print (newname)

def convert_it(ev=None):
	os.system('cwebp -quiet -preset %s -q %d %s -o %s' % (var1.get(), scale.get(), file_name, newname))
	sys.exit(0)

top.title("PNG-2-WEBP")
img = Image.open(file_name)
img = img.resize((260, 210), Image.ANTIALIAS)
tk_img = ImageTk.PhotoImage(img)
imagepanel=Label(top,image = tk_img)
imagepanel.grid(row =0, column=0,rowspan=1,columnspan=2, padx=2,pady=10)

label = Label(top, text='Image Type', font='Sans -12 bold')
label.grid(row =1, column=0, padx=2,pady=10)
var1 = StringVar(top)
var1.set('default')
choices = ['default', 'picture', 'photo', 'drawing','icon', 'text']
option = OptionMenu(top, var1, *choices)
option.config(width=14)
option.grid(row =1, column=1, padx=2,pady=10)

label1 = Label(top, text='Output Quality', font='Sans -12 bold',width=16)
label1.grid(row =2, column=0, padx=2,pady=10)

scale = Scale(top, from_=10, to=100,  orient=HORIZONTAL,resolution=5,tickinterval=40,sliderlength=15,length=180)
scale.config(width=20)
scale.set(85)
scale.grid(row =2, column=1, padx=2,pady=10)

quit = Button(top, text='Never Mind', command=top.quit, activeforeground='white', activebackground='red',width=14)
quit.grid(row =3, column=0, padx=16,pady=10)
commit = Button(top, text='Convert', command=convert_it, activeforeground='white', activebackground='green',width=16)
commit.grid(row =3, column=1, padx=2,pady=10)

mainloop()