# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-07-18 07:20
from __future__ import unicode_literals

from django.db import migrations, models
import requests

def grab_http_stuff(apps) -> None:
    Page = apps.get_model("calligraphy", "Page")
    Char = apps.get_model("calligraphy", "Character")
    pages = Page.objects.all()
    r_blank = requests.get('http://www.cadal.zju.edu.cn/NewCalligraphy/GetPageSize')
    for page in pages:
        chars = Char.objects.filter(parent_page=page.id)
        print("----------------------------------------------------")
        if(len(chars) > 0):   # here I make the assumption that individual pages always have the same dimensions and 
                              # the same fransformaiton methods.  I do this to reduce download time
            char = chars[0]
            page_id = str(page.page_id).zfill(8)
            payload = {'bookID': str(page.book_id).zfill(8),
                       'pageID': page_id,
                       'characterFile': page_id + '(' + str(char.x1) + ',' + str(char.y1) + ',' + str(char.x2) + ',' + str(char.y2) + ')'}
            r = r_blank
            while(r.text == ''):  #Server has a problem where the response is sometimes empty
                r = requests.get('http://www.cadal.zju.edu.cn/NewCalligraphy/GetPageSize', params=payload)
                print(payload)
                print(r.text)
            split1 = r.text.split('-') # 4607-6444#old : <width>-<height>#<char type>
            width = int(split1[0])
            split2 = split1[1].split('#')
            height = int(split2[0])
            char_type = split2[1]
            page.image_width_httpRequest = width
            page.image_length_httpRequest = height
            page.image_type_httpRequest = char_type
            page.save()



def import_data(apps, schemd_editor) -> None:
    grab_http_stuff(apps)

class Migration(migrations.Migration):

    dependencies = [
        ('calligraphy', '0013_auto_20160405_0846'),
    ]

    operations = [
        migrations.AddField(
            model_name='page',
            name='image_length_httpRequest',
            field=models.IntegerField(null=True),
        ),
        migrations.AddField(
            model_name='page',
            name='image_type_httpRequest',
            field=models.CharField(blank=True, max_length=64),
        ),
        migrations.AddField(
            model_name='page',
            name='image_width_httpRequest',
            field=models.IntegerField(null=True),
        ),
        migrations.RunPython(import_data)
    ]
