#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import

from django.template import Context, Template
from django.core.urlresolvers import resolve
from django.conf import settings
from django.core.handlers.wsgi import WSGIRequest
from django.shortcuts import HttpResponse

from .models import Html

import tempfile
import time
import os
import subprocess


class InstanceError(Exception):
    pass


class WkHtmlToPdfError(Exception):
    pass


class WKHtmlToPDFGenerator(object):
    """
        Wkhtmltopdf generator, it will take context and html converts to pdf.
    """
    def __init__(self, **kwargs):
        """
        By default it will search django core settings,
        if wkhtmltopdf not found there it will add that command.
        :param kwargs:
        It may contains the html and context,
        html object is model and context of view
        :type kwargs: Dictionary
        :returns: None
        """
        tempfile.tempdir = '/tmp/'
        self.tmp_dir = tempfile.gettempdir()
        self.html = kwargs.get('html')
        self.context = kwargs.get('context')
        self.command = []
        self.code_format = "utf-8"
        if hasattr(settings, "WKHTML_TO_PDF_CMD") and isinstance(settings.WKHTML_TO_PDF_CMD, str):
            self.command = [settings.WKHTML_TO_PDF_CMD]

    @property
    def _get_options(self):
        """ Providing external options for wkhtmltopdf from settings
            and HtmlHeaderFooter model
        """
        if self.html.htmlheader.quiet:
            self.command.append('--quiet')
        if self.html.htmlheader.zoom:
            self.command.extend(['--zoom', str(self.html.htmlheader.zoom)])
        # default to UTF-8 encoding.  Use <meta charset="latin-1"> to override.
        self.command.extend(['--encoding', self.html.htmlheader.encode_type])

        options = getattr(settings, 'WKHTML_OPTIONS', None)
        if options is not None:
            if not isinstance(options, dict):
                raise InstanceError("WKHTML_OPTIONS not a dictionary")
            for key, value in options.iteritems():
                if value is None:
                    self.command.append(str(key))
                else:
                    self.command.extend([str(key), str(value)])

    def _write_data_into_file(self, content, name, file_to_del, css=False):
        """It will creates the temp file in temporary folder
        :param: content: context of view
        :type: content: Dictionary
        :param: name:
        html or css file suffix
        :type: name: str or unicode
        :param: file_to_del:
        it will holds the temp files for after delete those
        files from temp folder when pdf generate complete.
        :type: file_to_del: list
        :param: css:
        By default it is False, If it provides then this suffix is css.
        :type: css: bool
        :returns: temp file object
        """
        encoded_content = content.encode(self.code_format)
        if not css:
            _sanitize_string = self._sanitize_html(encoded_content)
        else:
            _sanitize_string = encoded_content
        render_str = self._render_string(_sanitize_string)
        com_file = file(
            os.path.join(self.tmp_dir, str(time.time()) + name), 'w'
        )
        com_file.write(render_str.encode(self.code_format))