#!/usr/bin/env python3
import sys
import subprocess
import os
import re
import tempfile
import shutil
import locale
import gettext

try:
    translation = gettext.translation('enmarcado',localedir='/usr/share/locale')
    if translation:
        translation.install()
        _ = translation.gettext
except FileNotFoundError:
    print('No translation found!')
    _ = lambda x: x

RESOURCE_DIR='/usr/lib/enmarcado/resources/enmarcado'

mode=''
template=''
imgs=[]

def help(exitcode=0):
    print()
    print(f"{os.path.basename(sys.argv[0])} -m <MODE> -t <TEMPLATE> file1 [file2] [file3]")
    print(f"{os.path.basename(sys.argv[0])} -h")
    print()
    print("<MODE> = [horizontal|vertical]")
    t=[]
    t='|'.join(os.listdir(f'{RESOURCE_DIR}/horizontal'))
    print(f"<TEMPLATE> = [{t}]")
    print('')
    print()
    sys.exit(exitcode)

def parse_parameters():
    global mode, template, imgs
    try:
        narg = 0
        while narg < len(sys.argv)-1:
            narg += 1
            param = sys.argv[narg]
            if param == "-m":
                if narg+1 < len(sys.argv):
                    mode = sys.argv[narg+1]
                    narg += 1
                else:
                    raise Exception(_('No mode selected'))
            elif param == "-t":
                if narg+1 < len(sys.argv):
                    template = sys.argv[narg+1]
                    narg += 1
                else:
                    raise Exception(_('No template selected'))
            else:
                if param == '-h':
                    help()
                param=os.path.realpath(param)
                if os.path.isfile(param):
                    if len(imgs) < 3:
                        imgs.append(param)
                else:
                    raise Exception(_('{} not exists').format(param))
    except Exception as e:
        print(f'{e}')
        help(1)

def image_size(imgname):
    magic = subprocess.check_output(['/usr/bin/identify',imgname]).decode()
    size = magic.split(' ')[2]
    try:
        sizes = re.findall(r'(\d+)[ ]?x[ ]?(\d+)', size)[0]
        if size != '{}x{}'.format(sizes[0],sizes[1]):
            raise Exception('Unknown image size')
        return (int(sizes[0]),int(sizes[1]))
    except Exception as e:
        print(f'{e}')
        sys.exit(1)

def resize(imgname):
    os.chdir(os.path.dirname(imgname))
    subprocess.check_call(['/usr/bin/convert',imgname,'-alpha','remove','-resize','500',imgname])

def make_square(imgname):
    os.chdir(os.path.dirname(imgname))
    subprocess.check_call(['/usr/bin/convert',imgname,'-background','white','-trim','+repage',imgname])
    x,y=image_size(imgname)
    if x > y:
        subprocess.check_call(['/usr/bin/mogrify','-gravity','center','-background','white','-extent',f'{x}x{x}',imgname])
    if y > x:
        subprocess.check_call(['/usr/bin/mogrify','-gravity','center','-background','white','-extent',f'{y}x{y}',imgname])

def ask(default_name):
    try:
        if not default_name:
            return None
        return subprocess.check_output(['/usr/bin/kdialog','--getsavefilename',default_name,'application/pdf']).decode().strip()
    except Exception as e:
        return None

def ask_open(filename):
    try:
        subprocess.check_call(['/usr/bin/kdialog','--yesno',_(' Open {} ?').format(filename),'--title',os.path.basename(sys.argv[0])])
        return True
    except:
        return False

# MAIN PROGRAM

if __name__ == "__main__":
    parse_parameters()
    if not mode or not template or not imgs:
        print(_('Wrong parameters'))
        help(1)
    directory = f'{RESOURCE_DIR}/{mode}/{template}'
    template_name = f'p{len(imgs)}.svg'
    if not os.path.isdir(directory):
        print(_('Wrong mode or template'))
        help(1)
    if not os.path.isfile(f'{directory}/{template_name}'):
        print(_('Template {} not found!').format(template_name))
        help(1)

    out_pdf=''
    out_png=''
    with tempfile.TemporaryDirectory() as dirname:
        file_template=f'{dirname}/{template_name}'
        file_pdf=f'{dirname}/{template_name.replace(".svg",".pdf")}'
        file_png=f'{dirname}/{template_name.replace(".svg",".png")}'
        shutil.copy(f'{directory}/{template_name}',file_template)
        imagenames=['UNO','DOS','TRES']
        n=-1
        for img in imgs:
            # newfile=f'{dirname}/{os.path.basename(img)}'
            n+=1
            imagename=imagenames[n]
            newfile=f'{dirname}/{imagename}'
            shutil.copy(img,newfile)
            x,y=image_size(newfile)
            if x not in range(500) and y not in range(500):
                resize(newfile)
            make_square(newfile)
        os.chdir(dirname)
        subprocess.check_call(['/usr/bin/rsvg-convert',file_template,'-f','png','-b','white','-o',file_png])
        subprocess.check_call(['/usr/bin/rsvg-convert',file_template,'-f','pdf','-b','white','-o',file_pdf])
        if imgs:
            basename = os.path.dirname(os.path.realpath(imgs[0]))
        else:
            basename = os.path.expanduser('~')
        output = ask(f'{basename}/{mode}_{template}.pdf')
        if output:
            out_png=f'{os.path.dirname(output)}/{os.path.basename(output).replace(".pdf",".png")}'
            out_pdf=f'{os.path.dirname(output)}/{os.path.basename(output).replace(".pdf",".pdf")}'
            shutil.copy(file_png,out_png)
            shutil.copy(file_pdf,out_pdf)
        else:
            sys.exit(0)
    if ask_open(f'{os.path.basename(output).replace(".pdf",".pdf")}'):
        subprocess.Popen(['/usr/bin/okular',f'{out_pdf}'],stderr=subprocess.DEVNULL)
    sys.exit(0)
