#! /usr/bin/env python
#  -*- coding: utf-8 -*-
#
# Support module generated by PAGE version 6.0
#  in conjunction with Tcl version 8.6
#    Jan 14, 2021 11:47:32 AM EET  platform: Linux
#    Jan 16, 2021 05:07:26 PM EET  platform: Linux

import sys
import os
import glob
from PIL import Image, ImageTk
from cropperhandler import CropperHandler

try:
    import Tkinter as tk
except ImportError:
    import tkinter as tk

try:
    import ttk

    py3 = False
except ImportError:
    import tkinter.ttk as ttk

    py3 = True

# picture class and original crop coordinates
_crop_handler: CropperHandler
# canvas rectangle handle
_rect = None
# files to process
_pic_files = None


def init(top, gui, *args, **kwargs):
    global w, top_level, root
    global _pic_files
    w = gui
    top_level = top
    root = top
    # own inits
    _folder = os.path.abspath(".")
    w.btn_working_folder.configure(text=_folder)
    _pic_files = get_pic_files(_folder)


def get_pic_files(_path):
    # get all pic files
    _infiles = glob.glob(_path + "/*.jpg")
    for i, val in enumerate(_infiles):
        _infiles[i] = os.path.basename(_infiles[i])
    return _infiles


def a_btnCrop(p1):
    print("croppergui_support.a_btnCrop")
    _crop_handler.save_crop(_crop_handler._limits)
    # take next pic
    a_btnNext(p1)
    sys.stdout.flush()


# scale cropping to canvas
def _calc_crop_lines(cropper: CropperHandler, org_coords):
    _clines = [0] * 4

    _org_size = cropper.get_image().size
    _x_scale = w.canvPhoto.winfo_width() / _org_size[0]
    _y_scale = w.canvPhoto.winfo_height() / _org_size[1]
    _clines[0] = org_coords[0] * _x_scale
    _clines[1] = org_coords[2] * _y_scale
    _clines[2] = org_coords[1] * _x_scale
    _clines[3] = org_coords[3] * _y_scale
    return _clines


def a_btnNext(p1):
    global _rect
    global _crop_handler
    global _pic_files
    print("croppergui_support.a_btnNext")
    sys.stdout.flush()

    if len(_pic_files) == 0:
        w.canvPhoto.delete("all")
        return
    _crop_handler = CropperHandler(_pic_files[0])
    del _pic_files[0]
    _crop_handler_coords = _crop_handler.find_edges()
    # load the image file and fit it to canvas
    ima = _crop_handler.get_image().resize(
        (w.canvPhoto.winfo_width(), w.canvPhoto.winfo_height()), Image.BILINEAR
    )
    photo = ImageTk.PhotoImage(ima)
    # put image on canvas
    w.canvPhoto.imageList = []
    id = w.canvPhoto.create_image(0, 0, image=photo, anchor=tk.NW)
    w.canvPhoto.imageList.append(photo)

    # crop lines to canvas
    _crop_lines = _calc_crop_lines(_crop_handler, _crop_handler_coords)
    _rect = w.canvPhoto.create_rectangle(
        _crop_lines[0],
        _crop_lines[1],
        _crop_lines[2],
        _crop_lines[3],
        outline="white",
        dash="2 4",
    )


def a_canv_mousewheel(p1):
    print("croppergui_support.a_canv_mousewheel")
    sys.stdout.flush()


# define on what section the pointer is on pic (use 20% rule)
def get_side(px):
    _side = "center"
    _add_crop = 1  # change magnitude (+/-) depends by edge
    _xcur = px.x  # cursor pos
    _ycur = px.y
    _cw = w.canvPhoto.winfo_width()  # canvas size
    _ch = w.canvPhoto.winfo_height()
    # define on which region the pointer is
    if _xcur < _cw * 0.20:
        _side = "left"
    elif _xcur > _cw * 0.80:
        _side = "right"
        _add_crop = -1
    elif _ycur < _ch * 0.20:
        _side = "up"
    elif _ycur > _ch * 0.80:
        _side = "down"
        _add_crop = -1

    return _side, _add_crop


def a_canv_scroll_down(p1):
    global _rect
    global _crop_handler
    # delete prev crop
    w.canvPhoto.delete(_rect)
    # add crop lines
    _side, _add = get_side(p1)
    _clines = _crop_handler.change_edge(_side, -10 * _add)
    _crop_lines = _calc_crop_lines(_crop_handler, _clines)
    _rect = w.canvPhoto.create_rectangle(
        _crop_lines[0],
        _crop_lines[1],
        _crop_lines[2],
        _crop_lines[3],
        outline="white",
        dash="2 4",
    )
    print("croppergui_support.a_canv_scroll_down")
    sys.stdout.flush()


def a_canv_scroll_up(p1):
    global _rect
    global _crop_handler
    # delete prev crop
    w.canvPhoto.delete(_rect)
    # add crop lines
    _side, _add = get_side(p1)
    _clines = _crop_handler.change_edge(_side, +10 * _add)
    _crop_lines = _calc_crop_lines(_crop_handler, _clines)
    _rect = w.canvPhoto.create_rectangle(
        _crop_lines[0],
        _crop_lines[1],
        _crop_lines[2],
        _crop_lines[3],
        outline="white",
        dash="2 4",
    )
    print("croppergui_support.a_canv_scroll_up")
    sys.stdout.flush()


def a_btn_working_folder(p1):
    print("croppergui_support.a_btn_working_folder")
    sys.stdout.flush()


def destroy_window():
    # Function which closes the window.
    global top_level
    top_level.destroy()
    top_level = None


if __name__ == "__main__":
    import croppergui

    croppergui.vp_start_gui()
