# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-09-15 14:25
#
# This goes through and calculates the degree of overlap between features of origional and new characters
#  Note:  This does not correctly build against old chars, instead building against new chars twice
#
####################################################################

from __future__ import unicode_literals

from django.db import migrations

import numpy as np

def do_stuff(apps, schemd_editor) -> None:
    Char_val = apps.get_model('calligraphy', 'Character').objects
    Char_ori = apps.get_model('calligraphy', 'Character').objects
    Pages = apps.get_model('calligraphy', 'Page').objects
    DetectedBox = apps.get_model('calligraphy', 'DetectedBox').objects
    PagesHaveChars = apps.get_model('calligraphy', 'PagesHaveChars').objects
    for thisPage in PagesHaveChars.all():
        curPage = Pages.get(id=thisPage.haveChars.id)
        chars_val = Char_val.filter(parent_page=curPage)
        chars_ori = Char_ori.filter(parent_page=curPage)
        features  = DetectedBox.filter(parent_page=curPage)
        print(str(len(features)) + " " + str(len(chars_val)) + " " + str(len(chars_ori)))
        grid_val = np.zeros([curPage.image_length,curPage.image_width], dtype=np.uint8)
        grid_ori = np.zeros([curPage.image_length,curPage.image_width], dtype=np.uint8)
        for char_val in chars_val:
            grid_ori[char_val.y1:char_val.y2, char_val.x1:char_val.x2].fill(1)
        for char_orig in chars_ori:
            grid_val[char_orig.y1:char_orig.y2, char_orig.x1:char_orig.x2].fill(1)
        for feature in features:
            sum_val = np.sum(grid_val[feature.y1:feature.y2, feature.x1:feature.x2])
            sum_ori = np.sum(grid_ori[feature.y1:feature.y2, feature.x1:feature.x2])
            area = (feature.y2 - feature.y1) * (feature.x2 - feature.x1)
            feature.percent_inside_currated_box = int(100 * sum_val / area)
            feature.percent_inside_orig_box = int(100 * sum_ori / area)
            feature.save()

    

class Migration(migrations.Migration):

    dependencies = [
        ('calligraphy', '0125_auto_20170915_1416'),
    ]

    operations = [ migrations.RunPython(do_stuff)
    ]
