#!/usr/bin/env python
# -*- coding: utf-8 -*-

from gimpfu import * 
import ctypes
import os
from datetime import datetime

def mapload(image, drawable):

    # Merging steps
    pdb.gimp_image_undo_group_start(image)
    
    # Image size recognition and layer creation
    filename = pdb.gimp_layer_get_name(image.layers[0])
           
    sizewidth = drawable.width
    sizeheight = drawable.height

    layer1 = pdb.gimp_layer_new_from_drawable(drawable, image)
       
    # Edge detection using Sobel operator       
    pdb.plug_in_edge(image, drawable, 1, 0, 0)

    # Converting to gryscale according to the value parameter
    monochrome = TRUE
    rr_gain = 0.299
    rg_gain = 0.299
    rb_gain = 0.299
    gr_gain = 0.587
    gg_gain = 0.587
    gb_gain = 0.587 
    br_gain = 0.114
    bg_gain = 0.114
    bb_gain = 0.114
    
    pdb.plug_in_colors_channel_mixer(image, drawable, monochrome, rr_gain, rg_gain, rb_gain, gr_gain, gg_gain, gb_gain, br_gain, bg_gain, bb_gain)

    # Converting to monochrome    
    pdb.gimp_image_convert_grayscale(image)

    # Bit depth recognition
    bytres = drawable.bpp
    if pdb.gimp_drawable_has_alpha(drawable):
        depth = (256 ** (bytres / 2)) - 1
    else:
        depth = (256 ** bytres) - 1
    
    resolution = (int(pdb.gimp_image_get_resolution(image)[0]) + int(pdb.gimp_image_get_resolution(image)[1])) / 2  
    
    # Average pixel value recognition    
    histogram = pdb.gimp_drawable_histogram(drawable, 0, 0, 1)
    
    if bytres == 1 or (bytres == 2 and pdb.gimp_drawable_has_alpha(drawable)):
        ml = histogram[0] / depth * 100
    else:
        ml = histogram[0] * 100
    px = histogram[3]
        
    sizewidth = int(sizewidth / 10) + (sizewidth % 10 > 0)
    sizeheight = int(sizeheight / 10) + (sizeheight % 10 > 0)
    if sizewidth > sizeheight:
        pdb.plug_in_pixelize2(image, drawable, sizeheight, sizeheight)
    else:
        pdb.plug_in_pixelize2(image, drawable, sizewidth, sizewidth)   
    
    histogram2 = pdb.gimp_drawable_histogram(drawable, 0, 0, 1)
    
    if bytres == 1 or (bytres == 2 and pdb.gimp_drawable_has_alpha(drawable)):
        sd = histogram2[1] / depth * 100
    else:
        sd = histogram2[1] * 100
    
    pdb.gimp_image_convert_rgb(image)      
    layer2 = pdb.gimp_layer_new_from_drawable(drawable, image)
    
    pdb.gimp_layer_set_opacity(layer2, 85)
    pdb.gimp_image_insert_layer(image, layer1, None, -1)
    pdb.gimp_image_insert_layer(image, layer2, None, -1)    
    
    # Writing a report file
    now = datetime.now()
    current_time = now.strftime("%Y%m%d_%H%M%S")       
    if not(os.path.isfile("gmlmt_report.txt") and os.path.getsize("gmlmt_report.txt") > 0):
        reportfile = open("gmlmt_report.txt","a")
        reportfile.write("cas_znacka\tnazev_souboru\tnapln_mapy_proc\tst_odch_proc\tpocet_pixelu\trozliseni\n")
        reportfile.close()

    reportfile = open("gmlmt_report.txt","a+")
    reportfile.write(current_time)
    reportfile.write("\t")
    reportfile.write(str(filename))
    reportfile.write("\t")
    reportfile.write(str(round(ml, 1)))
    reportfile.write("\t")
    reportfile.write(str(round(sd, 1)))
    reportfile.write("\t")
    reportfile.write(str(int(px)))
    reportfile.write("\t")
    if resolution == 100:
        reportfile.write("ok")
    else:
        reportfile.write(str(resolution))
    reportfile.write("\n")
    reportfile.close()
    
    # Value notification
    message = ""
    if resolution != 100:
        message = " Varování: Rozlišení obrazu je "  + str(resolution) + " DPI, zatímco doporučeno je 100 DPI.\n\n"  
    message = message + " Grafická náplň mapy: " + str(round(ml, 1)) + " %"
    ctypes.windll.user32.MessageBoxW(0, unicode(message, "utf-8"), u"VÝSLEDKY MĚŘENÍ", 0x40) 
        
    # Finishing merged steps
    pdb.gimp_image_undo_group_end(image)
    
register(
    "NAPLNMAPY_1-2",
    "Experimentální nástroj pro určování grafické náplně map založený na detekci hran",
    "Experimentální nástroj pro určování grafické náplně map založený na detekci hran pomocí Sobelova filtru, vyvinutý na Katedře geoinformatiky Univerzity Palackého v Olomouci v rámci výzkumu metrik pro výpočet grafické náplně map. Pro vzájemnou porovnatelnost se doporučuje využít rastry reprezentující mapu v originálních rozměrech a s rozlišením 100 DPI",
    "Radek Barvíř", "CC BY-SA", "v 1.2, build 210112, 2021",
    "GMLMT 1.2 (náplň mapy)",
    "RGB*", 
    [
        (PF_IMAGE, "image", "takes current image", None),
        (PF_DRAWABLE, "drawable", "Input layer", None)
    ],
    [],
    mapload, menu="<Image>/Filters/Edge-Detect")

main()