package com.rjconsultores.ventaboletos.web.gui.controladores.catalogos;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.util.HtmlUtils;
import org.zkforge.ckez.CKeditor;
import org.zkoss.util.resource.Labels;
import org.zkoss.zhtml.Messagebox;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zul.Borderlayout;
import org.zkoss.zul.Button;
import org.zkoss.zul.Comboitem;
import org.zkoss.zul.Image;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Vlayout;

import com.rjconsultores.ventaboletos.entidad.ImpresionLayoutConfig;
import com.rjconsultores.ventaboletos.enums.EnumLinguagemImpresion;
import com.rjconsultores.ventaboletos.rest.LabelaryService;
import com.rjconsultores.ventaboletos.service.ImpresionLayoutConfigService;
import com.rjconsultores.ventaboletos.utilerias.UsuarioLogado;
import com.rjconsultores.ventaboletos.web.utilerias.MyComboboxEstandar;
import com.rjconsultores.ventaboletos.web.utilerias.MyGenericForwardComposer;
import com.rjconsultores.ventaboletos.web.utilerias.MyListbox;
import com.rjconsultores.ventaboletos.web.utilerias.MyTextbox;

@SuppressWarnings("serial")
@Controller("editarImpresionLayoutConfigController")
@Scope("prototype")
public class EditarImpresionLayoutConfigController extends MyGenericForwardComposer {

	@Autowired
	private ImpresionLayoutConfigService impresionLayoutConfigService;
	private ImpresionLayoutConfig impresionLayoutConfig;
	private MyListbox impresionLayoutConfigList;
	private Button btnApagar;
	private MyTextbox txtNome;
	private MyComboboxEstandar cmbLinguagemImpresion;
	private CKeditor ckTexto;
	private List<EnumLinguagemImpresion> lsEnumLinguagemImpresion;
	private Vlayout layoutCkEditor;
	private Borderlayout layoutTextZpl;
	private Textbox txtTexto;
	private Image img;
	private static Logger log = LogManager.getLogger(EditarImpresionLayoutConfigController.class);

	@Override
	public void doAfterCompose(Component comp) throws Exception {
		
		lsEnumLinguagemImpresion = Arrays.asList(EnumLinguagemImpresion.values());
		
		super.doAfterCompose(comp);

		impresionLayoutConfig = (ImpresionLayoutConfig) Executions.getCurrent().getArg().get("impresionLayoutConfig");
		impresionLayoutConfigList = (MyListbox) Executions.getCurrent().getArg().get("impresionLayoutConfigList");

		if (impresionLayoutConfig.getImpresionLayoutConfigId() == null) {
			btnApagar.setVisible(Boolean.FALSE);
		} else {
			if (impresionLayoutConfig.getLinguagem() != null) {
				mudaLayout(impresionLayoutConfig.getLinguagem());
			}

		}

		ckTexto.setValue(impresionLayoutConfig.getTexto());

		if (StringUtils.isNotBlank(impresionLayoutConfig.getTexto())
				&& EnumLinguagemImpresion.ZPL.equals(impresionLayoutConfig.getLinguagem())) {
			img.setContent(new org.zkoss.image.AImage("preview.png", retornaImagem(impresionLayoutConfig.getTexto())));
		}
	}

	public void onClick$btnSalvar(Event ev) throws InterruptedException {
		txtNome.getValue();

		try {

			Comboitem cbLinguagemImpresion = cmbLinguagemImpresion.getSelectedItem();
			impresionLayoutConfig.setLinguagem(null);
			if (cbLinguagemImpresion != null) {
				impresionLayoutConfig.setLinguagem((EnumLinguagemImpresion) cbLinguagemImpresion.getValue());
			}

			impresionLayoutConfig.setTexto(ckTexto.getValue());
			impresionLayoutConfig.setActivo(Boolean.TRUE);
			impresionLayoutConfig.setFecmodif(Calendar.getInstance().getTime());
			impresionLayoutConfig.setUsuarioId(UsuarioLogado.getUsuarioLogado().getUsuarioId());

			if (impresionLayoutConfig.getImpresionLayoutConfigId() == null) {

				List<ImpresionLayoutConfig> lsImpresionLayoutConfigo = impresionLayoutConfigService
						.buscar(impresionLayoutConfig.getDescricao());

				if (!lsImpresionLayoutConfigo.isEmpty()) {
					Messagebox.show(Labels.getLabel("MSG.Registro.Existe"),
							Labels.getLabel("editarImpresionLayoutConfigController.window.title"), Messagebox.OK,
							Messagebox.EXCLAMATION);
					return;
				}

				impresionLayoutConfigService.suscribir(impresionLayoutConfig);
				impresionLayoutConfigList.addItemNovo(impresionLayoutConfig);
			} else {
				impresionLayoutConfigService.actualizacion(impresionLayoutConfig);
				impresionLayoutConfigList.updateItem(impresionLayoutConfig);
			}

			Messagebox.show(Labels.getLabel("editarImpresionLayoutConfigController.MSG.suscribirOK"),
					Labels.getLabel("editarImpresionLayoutConfigController.window.title"), Messagebox.OK,
					Messagebox.INFORMATION);

			closeWindow();

		} catch (Exception ex) {
			log.error("editarImpresionLayoutConfigController: " + ex);
			Messagebox.show(Labels.getLabel("MSG.Error"),
					Labels.getLabel("editarImpresionLayoutConfigController.window.title"), Messagebox.OK,
					Messagebox.ERROR);
		}
	}

	public void onClick$btnApagar(Event ev) throws InterruptedException {

		int resp = Messagebox.show(Labels.getLabel("editarImpresionLayoutConfigController.MSG.borrarPergunta"),
				Labels.getLabel("editarImpresionLayoutConfigController.window.title"), Messagebox.YES | Messagebox.NO,
				Messagebox.QUESTION);

		if (resp == Messagebox.YES) {

			impresionLayoutConfigService.borrar(impresionLayoutConfig);

			Messagebox.show(Labels.getLabel("editarImpresionLayoutConfigController.MSG.borrarOK"),
					Labels.getLabel("editarImpresionLayoutConfigController.window.title"), Messagebox.OK,
					Messagebox.INFORMATION);

			impresionLayoutConfigList.removeItem(impresionLayoutConfig);

			closeWindow();
		}
	}

	public void onChange$cmbLinguagemImpresion(Event ev) {
		Comboitem cbiLinguagemImpresion = cmbLinguagemImpresion.getSelectedItem();
		if (cbiLinguagemImpresion != null) {
			mudaLayout(cbiLinguagemImpresion.getValue());
		}
	}

	private void mudaLayout(Object object) {

		if (object != null) {
			EnumLinguagemImpresion enumLinguagemImpresion = (EnumLinguagemImpresion) object;

			switch (enumLinguagemImpresion) {
			case HTML:
				layoutCkEditor.setVisible(true);
				layoutTextZpl.setVisible(false);
				break;
			case ZPL:
				layoutCkEditor.setVisible(false);
				layoutTextZpl.setVisible(true);
				break;
			default:
				break;
			}

		}

	}

	public void onClick$btnRedesenhar(Event ev) throws InterruptedException {

		try {
			img.setContent(new org.zkoss.image.AImage("preview.png", retornaImagem(txtTexto.getText())));
		} catch (IOException e) {
			log.error("editarImpresionLayoutConfigController: " + e);
			Messagebox.show(e.getLocalizedMessage(),
					Labels.getLabel("editarImpresionLayoutConfigController.window.title"), Messagebox.OK,
					Messagebox.ERROR);
		}
	}

	private InputStream retornaImagem(String texto) {
		return LabelaryService.getInstance().retornarImagem(HtmlUtils.htmlEscape(texto));
	}

	public ImpresionLayoutConfigService getImpresionLayoutConfigService() {
		return impresionLayoutConfigService;
	}

	public void setImpresionLayoutConfigService(ImpresionLayoutConfigService impresionLayoutConfigService) {
		this.impresionLayoutConfigService = impresionLayoutConfigService;
	}

	public ImpresionLayoutConfig getImpresionLayoutConfig() {
		return impresionLayoutConfig;
	}

	public void setImpresionLayoutConfig(ImpresionLayoutConfig impresionLayoutConfig) {
		this.impresionLayoutConfig = impresionLayoutConfig;
	}

	public MyListbox getImpresionLayoutConfigList() {
		return impresionLayoutConfigList;
	}

	public void setImpresionLayoutConfigList(MyListbox impresionLayoutConfigList) {
		this.impresionLayoutConfigList = impresionLayoutConfigList;
	}

	public Button getBtnApagar() {
		return btnApagar;
	}

	public void setBtnApagar(Button btnApagar) {
		this.btnApagar = btnApagar;
	}

	public MyTextbox getTxtNome() {
		return txtNome;
	}

	public void setTxtNome(MyTextbox txtNome) {
		this.txtNome = txtNome;
	}

	public CKeditor getCkTexto() {
		return ckTexto;
	}

	public void setCkTexto(CKeditor ckTexto) {
		this.ckTexto = ckTexto;
	}

	public MyComboboxEstandar getCmbLinguagemImpresion() {
		return cmbLinguagemImpresion;
	}

	public void setCmbLinguagemImpresion(MyComboboxEstandar cmbLinguagemImpresion) {
		this.cmbLinguagemImpresion = cmbLinguagemImpresion;
	}

	public List<EnumLinguagemImpresion> getLsEnumLinguagemImpresion() {
		return lsEnumLinguagemImpresion;
	}

	public void setLsEnumLinguagemImpresion(List<EnumLinguagemImpresion> lsEnumLinguagemImpresion) {
		this.lsEnumLinguagemImpresion = lsEnumLinguagemImpresion;
	}

}
