#   pdf-segmented: Generate PDFs using separate compression for foreground and background
#   Copyright (C) 2025  Lee Yingtong Li
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU Affero General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU Affero General Public License for more details.
#
#   You should have received a copy of the GNU Affero General Public License
#   along with this program.  If not, see <https://www.gnu.org/licenses/>.

from . import CompressedLayer
from ..util import assert_has_cjb2

from PIL import Image

from dataclasses import dataclass
import io
import os
import subprocess
import tempfile

@dataclass
class JB2Layer(CompressedLayer):
	filename: str
	
	def cleanup(self):
		os.unlink(self.filename)

def jb2_compress_layer(layer: Image, dpi: float, tempdir: str) -> JB2Layer:
	assert_has_cjb2('JB2 compression requires DjVuLibre')
	
	# Save image to PPM temporarily
	_, pbm_file = tempfile.mkstemp(suffix='.pbm', dir=tempdir)
	layer.convert('1').save(pbm_file, format='ppm')
	
	# Convert image to JB2
	_, jb2_file = tempfile.mkstemp(suffix='.djvu', dir=tempdir)
	subprocess.run(['cjb2', '-dpi', str(round(dpi)), pbm_file, jb2_file], check=True)
	
	# Clean up
	os.unlink(pbm_file)
	
	return JB2Layer(filename=jb2_file)