##!/usr/bin/python
# -*-coding:UTF-8-*-

from PIL import Image
import os
import sys
import time
import py_load


def low_txt_re(txtval):
    """
    low text
    :param txtval:
    :return:
    """

    low_list = []
    low_txt = ""
    if isinstance(txtval, list):
        for i in txtval:
            low_list.append(i.strip().lower())
        return low_list
    elif isinstance(txtval, str):
        low_txt = txtval.strip().lower()
        return low_txt
    else:
        return txtval


def chk_agif(imgfile):
    # suit a_gif a_webp
    i = imgfile
    img = Image.open(i)

    try:
        img.seek(img.tell() + 1)
        return 0
    except Exception as e:
        return 1


def pimg2pdf(pdffn, img_files_list):
    # print(pdf_paths)
    package_fname_list = []
    package_bookmn_list = []

    print("Image %s to be packed, please wait ..." % (len(img_files_list)))

    # low the images file txt
    img_files_list = low_txt_re(img_files_list)

    for img_path in img_files_list:
        package_fname_list.append(img_path.split("/")[-1])
        package_bookmn_list.append(img_path.split("/")[-1].split(".")[0])

    file_list = img_files_list
    pic_name = []
    im_list = []
    for x in file_list:
        if ".jpg" in x or '.jpeg' in x or '.png' in x or '.bmp' in x or '.gif' in x or '.tiff' in x or '.tif' in x or \
                '.webp' in x:
            pic_name.append(x)

    # sort by txt alphabeat
    # pic_name.sort()

    new_pic = []
    false_pic = []

    for x in pic_name:
        # check_not animation_gif
        imgfile = x

        if chk_agif(imgfile) == 1:
            if ".jpg" in x:
                new_pic.append(x)
            if ".jpeg" in x:
                new_pic.append(x)
            if ".png" in x:
                new_pic.append(x)
            if ".bmp" in x:
                new_pic.append(x)
            if ".gif" in x:
                new_pic.append(x)
            if ".tiff" in x:
                new_pic.append(x)
            if ".tif" in x:
                new_pic.append(x)
            if ".webp" in x:
                new_pic.append(x)
        else:
            false_pic.append(x)
            pass
    # dbug_msg
    # print("hec", new_pic)

    im1 = Image.open(new_pic[0])
    # remove list 1
    # new_pic.pop(0)

    # loadbar_prepare
    max_steps = len(new_pic)
    process_bar = py_load.ShowProcess(max_steps)

    # limited the batch image number
    if max_steps > 50:
        print("Attention: the number of pictures compressed in batch is limited to less than 50!")
        print("Operation stop.")
        exit()

    for i in new_pic:
        img = Image.open(i)
        if img.mode == "RGBA":
            img = img.convert('RGB')
            im_list.append(img)
        else:
            im_list.append(img)

        # loadbar
        process_bar.show_process()
        time.sleep(0.02)

    process_bar.close()

    keywords_val = "Package by: " + ", ".join(new_pic)

    im1.save(pdffn, "PDF", resolution=100.0, save_all=True, append_images=im_list[1:], author="Ezone",
             keywords=keywords_val)
    print("Completed! Output file:", pdffn)
    if len(false_pic) > 0:
        print("Cannot be packed: {}".format(", ".join(false_pic)))


def b_pimg2pdf(path, pdf_name, rev=""):
    file_list = os.listdir(path)
    # low the txtval
    file_list = low_txt_re(file_list)

    # debug_msg
    # print(file_list)

    print("Image %s to be packed, please wait ..." % (len(file_list)))

    pic_name = []
    im_list = []
    for x in file_list:
        if ".jpg" in x or '.jpeg' in x or '.png' in x or '.bmp' in x or '.gif' in x or '.tiff' in x or '.tif' in x or \
                '.webp' in x:
            pic_name.append(x)

    new_pic = []
    false_pic = []

    for x in pic_name:
        # check_not animation_gif
        imgfile = os.path.join(path, x)

        if chk_agif(imgfile) == 1:
            if ".jpg" in x:
                new_pic.append(x)
            if ".jpeg" in x:
                new_pic.append(x)
            if ".png" in x:
                new_pic.append(x)
            if ".bmp" in x:
                new_pic.append(x)
            if ".gif" in x:
                new_pic.append(x)
            if ".tiff" in x:
                new_pic.append(x)
            if ".tif" in x:
                new_pic.append(x)
            if ".webp" in x:
                new_pic.append(x)
        else:
            false_pic.append(x)
            pass

    # debug msg
    # print("oral_list", new_pic)

    if rev == 1:
        # sort by alphabeta
        new_pic.sort()
    elif rev == 0:
        new_pic.sort(reverse=True)
    else:
        pass

    # debug msg
    # print("sorted_list", new_pic)

    im1 = Image.open(os.path.join(path, new_pic[0]))

    # remove list 1 [1:] daiti
    # new_pic.pop(0)

    # loadbar_prepare
    max_steps = len(new_pic)
    process_bar = py_load.ShowProcess(max_steps)

    # limited the batch image number
    if max_steps > 50:
        print("Attention: the number of pictures compressed in batch is limited to less than 50!")
        print("Operation stop.")
        exit()

    for i in new_pic:
        img = Image.open(os.path.join(path, i))
        if img.mode == "RGBA":
            img = img.convert('RGB')
            im_list.append(img)
        else:
            im_list.append(img)

        # loadbar
        process_bar.show_process()
        time.sleep(0.02)

    process_bar.close()

    keywords_val = "Package by: " + ", ".join(new_pic)

    im1.save(pdf_name, "PDF", resolution=100.0, save_all=True, append_images=im_list[1:], author="Ezone",
             keywords=keywords_val)
    print("Completed! Output file:", pdf_name)
    if len(false_pic) > 0:
        print("Cannot be packed: {}".format(", ".join(false_pic)))


# gif save
def gif_save(path, only_frame=True):
    im = Image.open(path)
    if only_frame == True:
        try:
            im.save('picframe{:02d}.png'.format(im.tell()))
            print("save as the singal frame of image")
        except Exception as e:
            print(e)

    else:
        try:
            im.save('picframe{:02d}.png'.format(im.tell()))
            while True:
                im.seek(im.tell() + 1)
                im.save('picframe{:02d}.png'.format(im.tell()))
        except Exception as e:
            print("Operate finish! Output all frame of image")


def gif_save_singal(path, only_frame=True):
    im = Image.open(path)
    im.save('picframe{:02d}.png'.format(im.tell()))


def convert_img(covimg_fn, format=""):
    """
    cov to any image format
    :param covimg_fn:
    :param format:
    :return:
    """
    if not covimg_fn:
        print("None image file to convert!")
        exit()
    outfile = ""
    for infile in covimg_fn:
        f, e = os.path.splitext(infile)
        if format.lower() == ("jpg", "jpeg"):
            outfile = f + ".jpg"
            print(outfile)
        elif format.lower() == "gif":
            outfile = f + ".gif"
            print(outfile)
        elif format.lower() == "png":
            outfile = f + ".png"
            print(outfile)
        elif format.lower() == "bmp":
            outfile = f + ".bmp"
            print(outfile)
        elif format.lower() == ("tif", "tiff"):
            outfile = f + ".tif"
            print(outfile)
        elif format.lower() == "webp":
            outfile = f + ".webp"
            print(outfile)
        else:
            print("Usage:Command <jpg|gif|bmp|png|tif|webp> filename1,filename2 ... ...")
            exit()

        if infile != outfile:
            try:
                Image.open(infile).save(outfile)
            except IOError:
                print("cannot convert:", infile)


if __name__ == '__main__':
    pass
