import locale
import logging
import os
from os.path import splitext, basename

import ghostscript

from django.conf import settings
from django.core.validators import ValidationError
from django.db import models
from django.urls import reverse
from django.utils import timezone
from django.utils.translation import gettext_lazy as _


logger = logging.getLogger("blackboard")


class JobPosting(models.Model):
    company_name = models.CharField(verbose_name="Firmenname", max_length=128)
    job_name = models.CharField(verbose_name="Berufsbezeichnung", max_length=128)

    salary = models.DecimalField(
        verbose_name="Gehalt",
        max_digits=6,
        decimal_places=1,
    )
    number_of_hours = models.DecimalField(
        default=40,
        verbose_name="Stundenanzahl",
        max_digits=3,
        decimal_places=1,
    )

    pdf_location = models.FileField(
        verbose_name="Stellenausschreibung", upload_to="uploads/blackboard/pdf/"
    )
    pdf_thumb_location = models.CharField(max_length=128)

    publish_date = models.DateField(
        verbose_name="Veröffentlichung", default=timezone.now
    )

    all_job_postings = models.Manager()

    class Meta:
        verbose_name = "Stellenausschreibung"
        verbose_name_plural = "Stellenausschreibungen"

    def __str__(self):
        return str(self.publish_date) + "_" + self.company_name + "_" + self.job_name

    def get_absolute_url(self):
        return reverse("blackboard")

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)

        if not os.path.exists(settings.MEDIA_ROOT + "uploads/blackboard/thumb/"):
            os.makedirs(settings.MEDIA_ROOT + "uploads/blackboard/thumb/")

        pdf_thumb_location_full = (
            settings.MEDIA_ROOT
            + "uploads/blackboard/thumb/"
            + splitext(basename(self.pdf_location.name))[0]
            + ".jpg"
        )

        self.pdf_thumb_location = (
            "/files/uploads/blackboard/thumb/"
            + splitext(basename(self.pdf_location.name))[0]
            + ".jpg"
        )

        self.pdf2jpeg(self.pdf_location.path, pdf_thumb_location_full)
        logger.info("SavenThumbAs: " + self.pdf_thumb_location)
        super().save(*args, **kwargs)
    
    def clean(self):
        count = 0
        for i in self.pdf_location.name:
            if i == ".":
                count = count + 1
        if count > 1:  # if more than one dot in filename
            raise ValidationError(_("Keine Dateien mit >1 Punkten im Namen erlaubt."))

    def pdf2jpeg(self, pdf_input_path, jpeg_output_path):
        args = [
            "pef2jpeg",  # actual value doesn't matter
            "-dNOPAUSE",
            "-sDEVICE=jpeg",
            "-dDEVICEWIDTHPOINTS=600",
            "-dDEVICEHEIGHTPOINTS=800",
            "-sOutputFile=" + jpeg_output_path,
            pdf_input_path,
        ]

        encoding = locale.getpreferredencoding()
        args = [a.encode(encoding) for a in args]

        # ghostscript.Ghostscript(*args)
        with ghostscript.Ghostscript(*args) as g:
            ghostscript.cleanup()
