/*
 * This file (ZebraLabelPrinter.java) is part of DebGen-LabelPrintLib  developed by ASTRID Research.
 * All rights reserved. Reproduction, modification, use or disclosure
 * to third parties without express authority is forbidden.
 *
 *  Copyright ASTRID Research, Hungary, 2010.
 *
 *  ASTRID Research
 *  Headquaters: Csapó utca 42. Debrecen H-4029 HUNGARY
 *  Phone: +36-52-533-173        Fax: +36-52-533-174
 *  Web: http://www.astrid.hu    E-mail: info@astrid.hu
 *
 * Project name: DEBGEN-Biobank-Project.
 * File last modified at 2010.01.07 14:44
 */
package hu.astrid.debgen.labelprint.printer;

import hu.astrid.debgen.labelprint.domain.Label;
import hu.astrid.debgen.labelprint.exception.LabelPrintException;

import javax.print.*;
import java.util.List;

/**
 * @author inagy
 */
public class ZebraLabelPrinter extends AbstractLabelPrinter {

    /**
     * Return printServices.
     */
    protected PrintService[] getPrintServices() {
        return PrintServiceLookup.lookupPrintServices(null, null);
    }

    /**
     * Return the first Zebra printer if any.
     */
    public PrintService searchZebraPrinter() throws LabelPrintException {
        PrintService result = null;
        PrintService[] services = getPrintServices();
        for (PrintService currentService : services) {
            if (currentService.getName().toUpperCase().indexOf("ZEBRA") > -1) {
                result = currentService;
                break;
            }
        }
        return result;
    }

    /**
     * Implements AbstractLabelPrinter.printLabel(List<Label> labels).
     * @param labels The labels to print.
     */
    @Override
    public void printLabel(List<Label> labels) throws LabelPrintException {
        PrintService psService = getPrintService();
        if (psService == null) {
            psService = searchZebraPrinter();
        }
        if (psService == null) {
            throw new IllegalStateException("Printer not set.");
        }

        try {
            for (Label label : labels) {
                for (int i = 0; i < label.getCopies(); i++) {
                    DocPrintJob job = psService.createPrintJob();
                    job.print(createDoc(label), null);
                    sleep();
                }
            }
        } catch (PrintException e) {
            throw new LabelPrintException(e);
        }
    }

    /**
     * Sleep between printjobs.
     */
    private void sleep() {
        try {
            Thread.sleep(1000);
        } catch (Exception ex) {
            //IGNORED
        }
    }

    /**
     * Return Doc to print.
     * @param label The label to create Doc from.
     */
    private Doc createDoc(Label label) throws LabelPrintException {
        byte[] buffer = label.processTemplate().getBytes();
        DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
        Doc doc = new SimpleDoc(buffer, flavor, null);
        return doc;
    }
}
