package com.softgraf.vendas.model.bkup;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Enumeration;

import com.softgraf.vendas.model.rede.FtpUpload;
import com.softgraf.vendas.model.zip.Compactador;

import javafx.scene.control.TextArea;
import javafx.stage.Stage;

public class Backup extends Thread {

	private TextArea texto;
	private Stage stage;
	private String pathMysqlDump;   // path + "mysqldump.exe" (Windows) OU "mysqldump" (Linux)

	public Backup(Stage stage, TextArea texto, String pathMysqlDump) {
		this.stage = stage;
		this.texto = texto;
		this.pathMysqlDump = pathMysqlDump;
	}

	@Override
	public void run() {

		try {

			File tmpSql = File.createTempFile("vendas_bkup_", ".sql");
			File tmpZip = File.createTempFile("vendas_bkup_", ".zip");
			String arquivoSql = tmpSql.toString();
			String arquivoZip = tmpZip.toString();
			aviso("\nCriando arquivo temporário: " + arquivoSql);
			aviso("\nCriando arquivo temporário: " + arquivoZip);

			if (pathMysqlDump == null) {
				throw new IOException("\nErro: MysqlDump não encontrado!");
			}

			aviso("\nCriando script sql...");
			Mysqldump mysqldump = new Mysqldump("vendas", "root", "softgraf", arquivoSql, pathMysqlDump);
			mysqldump.start();
			mysqldump.join();

			aviso("\nZipando o script sql....");
			Compactador compactador = new Compactador(arquivoSql, arquivoZip, null);
			compactador.start();
			compactador.join();

			String ftpDestino = "softgraf.com/vendas_bkup_db/" + "vendas_bkup_" + macAddress() + "_" + new Date().toString().replace(' ', '_') + ".zip";
			String ftpUsuario = "cursojava@softgraf.com";
			String ftpSenha = "cursojava";
			aviso("\nFazendo upload para: " + ftpDestino);
			FtpUpload ftpUpload = new FtpUpload(arquivoZip, ftpDestino, ftpUsuario, ftpSenha);
			ftpUpload.iniciar();

			aviso("\nApagando arquivos temporários...");
			tmpSql.delete();
			tmpZip.delete();

			aviso("\nSUCESSO!!!");
			stage.setIconified(false);

		} catch (InterruptedException | IOException e) {
			e.printStackTrace();
			stage.setIconified(false);
			texto.appendText("\n" + e.getMessage());
		}
	}

	private void aviso(String msg) throws InterruptedException {
		System.out.println(msg);
		texto.appendText(msg);
		// dorme 100 milisegundos para dar chance de outro processo executar
		Thread.sleep(100);
	}

	// obtem o endereço da placa de rede
	private String macAddress() {
		StringBuffer macAddress = new StringBuffer();

		try {

			// tenta obter a interface de rede através do localhost (Windows)
			NetworkInterface ni = NetworkInterface.getByInetAddress(InetAddress.getLocalHost());

			// se não conseguir, pesquisa por todas as interfaces de rede (Linux)
			if (ni == null) {
				Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
				while (interfaces.hasMoreElements()) {
					ni = interfaces.nextElement();
					if (ni.getHardwareAddress() != null) {
						break;
					}
				}
			}

			if (ni != null) {  // se alguma interface foi encontrada...
				byte[] mac = ni.getHardwareAddress();
				for (int i = 0; i < mac.length; i++) {
					macAddress.append(String.format("%02X", mac[i]));
				}
			}

		} catch (SocketException | UnknownHostException e) {
			e.printStackTrace();
			texto.appendText(e.getMessage());
			stage.setIconified(false);
		}

		return macAddress.toString();
	}

}
