/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package com.arrebol.taxiservicios.beans;

import com.arrebol.taxiservicios.beans.admin.driver.DriverAddBean;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.print.PrinterJob;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import javafx.print.PrintQuality;
import javax.imageio.ImageIO;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintException;
import javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.MediaSize;
import javax.print.attribute.standard.MediaSizeName;
import javax.print.attribute.standard.PrinterResolution;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 *
 * @author pc one
 */
public class TicketMulta extends TaxiGenericBean {
    final Logger logger = LogManager.getLogger(DriverAddBean.class);
    
    private String contentTicket = "\n" + "::" + (char) 27 + (char) 112 + (char) 0 + (char) 10 + (char) 100
            + "     " + getFechaFormateada(new Date()) + "\n\n"
            + "{{tipo}}\n"
            + "=============================\n"
            + "CHOFER:\n"
            + "{{driver}}\n"
            + "MONTO: {{monto}}"
            + "\n"
            + "=============================\n"
            + "       " + getLoggedUser().getLocation().getBusinessName() + "\n"
            + "AGRADECE SU PREFERENCIA\n\n"
            + getLoggedUser().getLocation().getCompleteAddress() + "\n"
            + getLoggedUser().getLocation().getMunicipality() + ", " + getLoggedUser().getLocation().getState() + ".\n"
            + "RFC: " + getLoggedUser().getLocation().getRfc() + "\n"
            + "TEL. " + getLoggedUser().getLocation().getPhone() + "\n"
            + "\n\n"
            + "-------------------------------"
            + "\n\n";

    ;        

public TicketMulta(String driver, String monto,  Integer tipo) {
        switch(tipo) {
            case 2:
              this.contentTicket = this.contentTicket.replace("{{tipo}}", "Ingreso");
              break;
            case 3:
              this.contentTicket = this.contentTicket.replace("{{tipo}}", "Pago de multa");
              break;
            case 4:
              this.contentTicket = this.contentTicket.replace("{{tipo}}", "Estudio socioeconómico");
              break;
            default:
              this.contentTicket = this.contentTicket.replace("{{tipo}}", "OTRO");
          }        
        this.contentTicket = this.contentTicket.replace("{{driver}}", driver);
        this.contentTicket = this.contentTicket.replace("{{monto}}", monto);
        this.contentTicket = this.contentTicket.replace("{{img}}", monto);
    }

    public void printTest() {
        System.out.print(contentTicket);
    }

    public void print() {
        try {

            byte[] bytes = contentTicket.getBytes();
            Integer xMediaSize = 52;
            Integer yMediaSize = 74;
            
            String printerName = getLoggedUser().getLocation().getPrinter();
            PrintService pintService;
            if (printerName != null) {
                pintService = findPrinter(printerName);
                
                //Primera imprecion IMG
                DocFlavor flavor2 = DocFlavor.BYTE_ARRAY.JPEG;
                DocPrintJob job2 = pintService.createPrintJob();                
                PrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
                PrinterResolution printerResolution = new PrinterResolution(1920, 1080, PrinterResolution.DPI);
                attributes.add(printerResolution);
                MediaSizeName mediaSizeName = MediaSize.findMedia(xMediaSize, yMediaSize, MediaSize.MM);
                attributes.add(mediaSizeName);                
                Doc doc2 = new SimpleDoc(logoToByte(), flavor2, null);
                job2.print(doc2, attributes);
                //Segunda imprecion Contenido del Ticket          
                DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
                DocPrintJob job = pintService.createPrintJob();                                
                Doc doc = new SimpleDoc(bytes, flavor, null);
                job.print(doc, null);     
                
            } else {
                logger.error("Printer not found");
            }
        } catch (PrintException ex) {
            logger.error(ex);
        }
    }
        
     private byte[] logoToByte() {
       String rutaImagen = "C:/Users/pc one/Documents/NetBeansProjects/CarDriver/car-driver-web/src/main/webapp/assets/images/logo_sin_fondo.png";
       BufferedImage image = null;
       byte[] img = null;
        try {
            File file = new File(rutaImagen);
            InputStream is = new FileInputStream(file);
            image = ImageIO.read(is);
            is.close();
        } catch (IOException e) {
            System.out.println("Error to ImageIO in  logoToImageIO() " + e);
        }        
        try {
               img = toByteArrayAutoCropped(image);
        } catch (Exception e) {
            System.out.println("Error to toByteArrayAutoCropped() in  logoToImageIO() " + e);
        }        
        return img;
    }

    private byte[] toByteArrayAutoCropped(BufferedImage originalImage) throws Exception {
        Integer medidaXImagen = 90;
        Integer medidaYImagen = 90;
        int width = originalImage.getWidth();
        int height = originalImage.getHeight();
        double ratio = (double) height / width;
        
        if (ratio < 0.50) {
            int newHeight = (int) (width * 0.75);
            int y = (int) (height - newHeight) / 2;
            if (newHeight > height) {
                newHeight = height;
                y = 0;
            }
            BufferedImage croppedImage = originalImage.getSubimage(0, y, width, newHeight);
            originalImage = croppedImage;
        }
        
        Image tmp = originalImage.getScaledInstance(medidaXImagen, medidaYImagen, Image.SCALE_SMOOTH);
        BufferedImage scaledImage = new BufferedImage(medidaXImagen, medidaYImagen, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = scaledImage.createGraphics();
        g2d.drawImage(tmp, 0, 0, null);
        g2d.dispose();

        return toByteArray(scaledImage);
    }

    private byte[] toByteArray(BufferedImage image) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        boolean written = ImageIO.write(image, "png", baos);
        if (!written) {
            throw new Exception("Error al escribir la imagen en el array de bytes");
        }
        return baos.toByteArray();
    }
    
    public PrintService findPrinter(String nombre) {
        logger.info("Find printer");
        PrintService service = null;
        PrintService[] services = PrinterJob.lookupPrintServices();
        for (int i = 0; service == null && i < services.length; i++) {
            if (services[i].getName().contains(nombre)) {
                service = services[i];
            }
        }
        return service;
    }
    
    public static String getFechaFormateada(Date fecha) {
        SimpleDateFormat formato = new SimpleDateFormat("yyyy-MM-dd");
        return formato.format((Date) fecha);
    }
}
