
package com.mycompany.sigge;

import java.io.BufferedReader;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import javafx.geometry.Insets;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import org.json.JSONArray;
import org.json.JSONObject;
import javafx.util.Duration;
import javafx.scene.control.Label;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;


import javax.print.PrintService;
import java.awt.*;
import java.io.IOException;
import javax.print.PrintServiceLookup;
// table view with scrollable as an alert to the printerSetup

public class Formulario extends Application {

	private String authToken;

	@Override
	public void start(Stage primaryStage) {

		try {
			AppConfig config = ConfigManager.loadConfig();
			if (config == null || config.getAuthToken() == null) {
				throw new IllegalStateException("No hay token");
			}
			this.authToken = config.getAuthToken();

		} catch (IOException | ClassNotFoundException | IllegalStateException e) {
			return;
		}

		GridPane gp = new GridPane();
		gp.setPadding(new Insets(10));
		gp.setHgap(10);
		gp.setVgap(10);

		Label configLabel = new Label("Configuración de impresora");
		Button configBtn = new Button("Configurar");
		configBtn.setOnAction(e -> PrinterSetup.show());


		Label urlLabel = new Label("Ingrese la URL:");
		TextField urlField = new TextField();

		Button sendButton = new Button("Enviar");
		sendButton.setOnAction(e -> {
			if (!urlField.getText().isEmpty()) {
				hacerPeticion(urlField.getText());
			}
		});
;
		Circle statusCircle = new Circle(6,Color.GRAY);
		
		Timeline urlChecker = new Timeline(
			new KeyFrame(Duration.seconds(1),ev->{
				String url = urlField.getText();
				if(url == null || url.isEmpty()){
					statusCircle.setFill(Color.GRAY);
					return;
				}
				boolean ok = urlAvailable(url,1000);
				statusCircle.setFill(ok ? Color.LIMEGREEN : Color.RED);
			})
		);

		urlChecker.setCycleCount(Timeline.INDEFINITE);
		urlChecker.play();

		gp.add(configLabel, 0, 0);
		gp.add(configBtn, 1, 0);
		gp.add(urlLabel, 0, 1);
		gp.add(urlField, 1, 1);
		gp.add(new Label("Conexion de la URL:"),0,2);
		gp.add(statusCircle,1,2);
		gp.add(sendButton, 4, 4);

		primaryStage.setScene(new Scene(new VBox(gp), 450, 250));
		primaryStage.setTitle("Formulario");
		primaryStage.show();
	}

	private boolean urlAvailable(String urlAvailability,int timeoutMs){
		try {
			AppConfig config = ConfigManager.loadConfig();
			URL url = new URL(urlAvailability);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("HEAD");
			conn.setRequestProperty("Authorization","Bearer"+config.getAuthToken());
			conn.setConnectTimeout(timeoutMs);
			conn.setReadTimeout(timeoutMs);
			conn.setInstanceFollowRedirects(true);
			int code = conn.getResponseCode();
			return(code>=200 && code<500);
		}catch(Exception e){
			return false;
		}
	}
	
	private void hacerPeticion(String urlString) {
		try {
			AppConfig config = ConfigManager.loadConfig();

			URL url = new URL(urlString);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();

			connection.setRequestMethod("GET");
			connection.setRequestProperty(
				"Authorization",
				"Bearer " + config.getAuthToken()
			);

			if (connection.getResponseCode() != 200) {
				throw new IOException("HTTP " + connection.getResponseCode());
			}

			BufferedReader br = new BufferedReader(
				new InputStreamReader(connection.getInputStream())
			);

			StringBuilder response = new StringBuilder();
			String line;
			while ((line = br.readLine()) != null) {
				response.append(line);
			}
			br.close();

			JSONObject root = new JSONObject(response.toString());
			if (!root.optBoolean("success", false)) {
				return;
			}

			JSONArray data = root.getJSONArray("data");

			for (int i = 0; i < data.length(); i++) {
				JSONObject item = data.getJSONObject(i);

				String pedIde = item.getString("ped_ide");
				String pedCod = item.getString("ped_cod");

				PrintService printer = PrinterSetup.getPrinterByAlias(pedCod);

				if (printer == null) {
					System.out.println("No existe impresora para alias: " + pedCod);
					continue;
				}

				imprimirPedido(pedIde,pedCod, printer, config.getAuthToken());
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void imprimirPedido(
		String pedIde,
		String pedCod,
		PrintService printer,
		String token) {
		try {
			String printUrl
				= "https://demo.iuvade.com/sigge/api/restobar_imprimir/"
				+ "?ide=" + URLEncoder.encode(pedIde, "UTF-8")
				+ "&cod=" + URLEncoder.encode(pedCod, "UTF-8");

			URL url = new URL(printUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();

			conn.setRequestMethod("GET");
			conn.setRequestProperty("Authorization", "Bearer " + token);
			conn.setRequestProperty("Accept", "application/pdf");

			int status = conn.getResponseCode();
			System.out.println("HTTP STATUS: " + status);
			System.out.println("Content-Type: " + conn.getContentType());

			if (status != 200) {
				System.out.println("No se pudo generar el PDF");
				return;
			}

			byte[] pdfBytes = conn.getInputStream().readAllBytes();

			String header = new String(pdfBytes, 0, Math.min(8, pdfBytes.length));
			if (!header.startsWith("%PDF")) {
				System.out.println("⚠️ Respuesta no es PDF");
				return;
			}

//			PrinterSetup.printPdfAsImage(pdfBytes, printer);
//debugg************************
			System.out.println("Printer elegido: " + printer.getName());
			for (PrintService ps : PrintServiceLookup.lookupPrintServices(null, null)) {
				System.out.println("Detectado: " + ps.getName());
			}

			PrinterSetup.printPdfAsEscPosRaster(pdfBytes, printer);



		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	
/*	private void hacerPeticion(String urlString) {
		try {
			// Crear la URL y la conexión HTTP
			URL url = new URL(urlString);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();

			connection.setRequestMethod("GET");
			connection.setRequestProperty("Authorization", "Bearer " + authToken);

			int code = connection.getResponseCode();
			if (code < 200 || code >= 300) {
				throw new IOException("HTTP " + code);
			}

			// Leer la respuesta de la URL (en formato binario)
			try (InputStream is = connection.getInputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream()) {

				byte[] buffer = new byte[8192];
				int n;
				while ((n = is.read(buffer)) > 0) {
					bos.write(buffer, 0, n);
				}

				byte[] pdfBytes = bos.toByteArray();
				PrinterSetup.printPdf(pdfBytes);  // Enviar a la impresora

			} catch (IOException e) {
				e.printStackTrace();
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
*/	
	public static void main(String[] args) {
		launch(args);  
	}

}
