#!/usr/bin/env python3
################################################
# 2016-2018 by Paul Sherman <psherman2001@gmail.com> 
#  v2.0 - 11/09/2018									        
# 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 = """
R0lGODlhIAAgAIQZAAAAgAAAqgAAvzMzmTMzzABmMzNmMzNmZjNmmTNmzGZmzACZAACZM2aZmWaZ
zADMAGaZ/2bM/5nMzJnM/8zMmczMzMz/mf//Zv//mf///////////////////////////yH5BAEK
AB8ALAAAAAAgACAAAAX+4CeOZGmeaEoGqhm8cPyOgdCOAKHsfM+OA8BPNXBMjsikkjAY2IjGo0Si
VCaawaGpOJFcvhdqdeLABp9bIwb8HR/NTcCJy/6KkZA8Ey4s0et4CXtwZgBoH1wUbBZHZYSPTWhc
ExVrFEcQkJqSUUoRg5qFJJNKCqGEcqOdSaBNrVipqlWZWAkQEUdXcFoipEimAwSrE60Kc8PEwRBK
tFgKE8fMylWOTc/QW9e/vtvWSHPaRwQJRwcHrN7f2UkQBI0LCw1ITMMQvAPhDssTBw8PBVEI7EuS
4N41I/scLPD34FwVeRMK+nnWoECSfgwXGFlVAEFEgxEKNHzH0B8DBAU+HPYrEEHiKAUYHxg4YKBk
xgcaQ/o7QOAegoU2g5ZMmXHAvZhCkwL1Z7QEgFNQm/D6IKCq1atYs1qdeqOriRAAOw==
"""

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 = 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 JPEG file")
	sys.exit(0)
		
# if the filename passed is not a jpg
x = imghdr.what(file_name)
if not x == 'jpeg':
	top.withdraw()
	tkinter.messagebox.showinfo("Error", "file_name does not appear to be a valid JPEG image")
	sys.exit(0)
	
#----------------------------------------------------------------------------------------------------------------

pattern = re.compile(".jpg", 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("JPG-2-WEBP")
#top["bg"]="#AAAAAA"
#top.geometry('480x600')

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