import os
import subprocess
from pathlib import Path

import logging
logger = logging.getLogger(__name__)
import configuration
config = configuration.main_config["DOWNLOADS"]

shrink_sizes = []

def shrink_pdf(article):
    article_loc = Path(article.save_path) / article.file_name
    initial_size = article_loc.stat().st_size
    compressed_tmp = Path(config['default_download_path']) / "compressed.pdf"

    if article_loc.suffix != "pdf":
        return article # it probably was a youtube video
        
    c = subprocess.run(
        [
            "gs",
            "-sDEVICE=pdfwrite",
            "-dPDFSETTINGS=/screen",
            "-dNOPAUSE",
            "-dBATCH",
            f"-sOutputFile={compressed_tmp}", 
            f"{article_loc}"
        ],
        stdout=subprocess.PIPE, stderr=subprocess.PIPE
    )

    if c.returncode == 0:
        try:
            os.replace(compressed_tmp, article_loc)
        except OSError as e:
            logger.error(f"Compression ran but I could not copy back the file {e}")

        final_size = article_loc.stat().st_size
        shrink_sizes.append(initial_size - final_size)
        logger.info(f"Compression worked. Avg shrinkage: {int(sum(shrink_sizes)/len(shrink_sizes) / 1000)} KB")


    else:
        logger.error(f"Could not run the compression! {c.stderr.decode()} - {c.stdout.decode()}")
    
    return article
