package sklep.rest.ext;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import jakarta.ws.rs.WebApplicationException;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.ext.MessageBodyWriter;
import jakarta.ws.rs.ext.Provider;
import sklep.model_jpa.Product;
import sklep.model_jpa.ProductList;

@Provider
public class PdfWriter implements MessageBodyWriter<Object> {
    private static final MediaType PDF_TYPE = new MediaType("application", "pdf");

    @Override
    public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
        return (type == Product.class || type == ProductList.class) && PDF_TYPE.isCompatible(mediaType);
    }

    @Override
    public void writeTo(Object obj, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
                        MultivaluedMap<String, Object> httpHeaders, OutputStream output)
            throws IOException, WebApplicationException {

        String fileName = "products.pdf";
        if (obj instanceof Product) {
            Product product = (Product) obj;
            // fileName = product.getProductName().replace(' ', '_') + ".pdf";
            fileName = String.format("product%04d.pdf", product.getId());
        }
        // httpHeaders.add("Content-Disposition", "attachment;filename=" + fileName);
        httpHeaders.add("Content-Disposition", "inline;filename=" + fileName);
        ObslugaXSL obslugaXSL = new ObslugaXSL();
        obslugaXSL.wypiszPDF(obj, output);
    }

}


/* Jednak się nie przyda, ale tak można sprawdzić, czy typ opisuje List<Element>
    private static boolean isListOf(Type genericType, Class<Product> elementType) {
        if(genericType instanceof ParameterizedType pType) {
            if(pType.getRawType() == List.class && pType.getActualTypeArguments()[0] == elementType) {
                return true;
            }
        }
        return false;
    }
 */