#!/usr/bin/env python3
# Friday, 11/20/2020
################################################
# 2016-2020 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.   
################################################

	
from tkinter import *
import tkinter.messagebox
import os, sys, 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 JPEG file', filetypes=[('JPEG files', '.jpg')])
	if not file_name:	
		sys.exit(0)
else:
	file_name = ' '.join(sys.argv[1:])
	if not os.path.isfile(file_name):
		top.withdraw()
		tkinter.messagebox.showinfo("Error", "This script is meant to be passed a single JPEG file")
		sys.exit(0)

# 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)

#convert -resize 260x210 "input.png" "output.png"
subprocess.call(['convert', '-resize', '260x210', '-strip', file_name, '/tmp/88.png'])

img = Image.open("/tmp/88.png")
tk_img = ImageTk.PhotoImage(img)
os.remove("/tmp/88.png")
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(90)
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)

# center
w = top.winfo_reqwidth()
h = top.winfo_reqheight()
ws = top.winfo_screenwidth()
hs = top.winfo_screenheight()
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
top.geometry('+%d+%d' % (x, y)) ## this part allows you to only change the location
# make modal
os.system('sleep 1 && wmctrl -F -a "PNG-2-WEBP" -b add,above &')

mainloop()
