# -*- coding: utf-8 -*-
'''
Created on Feb 22, 2015

@author: ymh
'''
import logging
import os

from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import transaction

from hdalab.models.renkan import HdalabRenkanStateTransition


from subprocess import check_call




logger = logging.getLogger(__name__)

@transaction.atomic
def change_renkan_state(hda_renkan, state, message=None, author=None):

    if state != hda_renkan.state:

        HdalabRenkanStateTransition.objects.create(renkan=hda_renkan, from_state=hda_renkan.state, to_state=state, message=message, author=author)
        hda_renkan.state = state
        hda_renkan.save()


def renkan_capture_preview(hdalab_renkan):
    #get last state date or last modification date
    #states are ordered by ts
    folder_date = hdalab_renkan.renkan.modification_date
    states = hdalab_renkan.states
    state = None
    if states.count() > 0:
        state = states.all()[0]
    if state:
        folder_date =  state.ts

    rel_export_path_dir = "thumbnails/renkan/%04d/%02d/%02d" % (folder_date.year, folder_date.month, folder_date.day)
    export_path_dir = os.path.join(settings.MEDIA_ROOT,rel_export_path_dir)
    export_filename = "%s.png" % hdalab_renkan.renkan.rk_id

    export_path = os.path.join(export_path_dir, export_filename)
    rel_export_path = os.path.join(rel_export_path_dir, export_filename)

    if not os.path.exists(export_path_dir):
            try:
                os.makedirs(export_path_dir)
            except OSError, e:
                if e.errno != 17:
                    raise
                # time.sleep might help here
                pass

    preview_dim = getattr(settings, 'RENKAN_PREVIEW_DIM', (500,500))
    preview_wait = getattr(settings, 'RENKAN_PREVIEW_WAIT', 5000)

    preview_args = [
        getattr(settings,'RENKAN_PREVIEW_PHANTOMJS_PATH','phantomjs'),
        os.path.join(os.path.dirname(os.path.abspath(__file__)),'scripts/capture-phantomjs.js'),
        "%s%s%s?rk_id=%s" % (getattr(settings, 'FRONT_WEB_URL', settings.WEB_URL), settings.BASE_URL, reverse('renkan_full'),hdalab_renkan.renkan.rk_id),
        export_path,
        "--width=%d" % preview_dim[0],
        "--height=%d" % preview_dim[1],
        "--wait=%d" % preview_wait
    ]
    check_call(preview_args)

    hdalab_renkan.renkan.image = rel_export_path
    hdalab_renkan.renkan.save()

