package com.example.mqtt_connection;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.xml.validation.Validator;

import org.hibernate.validator.internal.constraintvalidators.bv.NullValidator;
import org.springframework.beans.factory.annotation.Autowired;
import com.opcua.client.opcua.ConnectionInfo;
import com.opcua.client.opcua.ConnectionInfoRepositary;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.combobox.ComboBox;
import com.vaadin.flow.component.dependency.CssImport;
import com.vaadin.flow.component.html.H1;
import com.vaadin.flow.component.html.Label;
import com.vaadin.flow.component.icon.Icon;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.radiobutton.RadioButtonGroup;
import com.vaadin.flow.component.select.Select;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.data.binder.BinderValidationStatus;
import com.vaadin.flow.data.binder.BindingValidationStatus;
import com.vaadin.flow.data.validator.StringLengthValidator;
import com.vaadin.flow.data.value.ValueChangeMode;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.theme.lumo.Lumo;

@CssImport("./styles/shared-styles.css")
//@CssImport(value = "./styles/vaadin-text-field-styles.css", themeFor = "vaadin-text-field")
@Route("tageditor")  
public class mqtt_tagtree_form extends VerticalLayout {
	String s;
	// Long id;
	@Autowired
	mqtt_tagtree_repository mq;
	@Autowired 
	tag_treerepository tg;
	@Autowired
	tag_editor_mqtt_repo mqtagrepo;
	@Autowired
	tag_treeservice tg1;
	@Autowired
	HttpServletRequest req;
	@Autowired
	Tag_Editor_opcua_Entity_repo opctagrepo;
    @Autowired
    tag_editor_modbus_repo modbustagrepo;
	@Autowired
	ConnectionInfoRepositary opcConn;
	Long tag_id;
	// String topic;
	Long id;
	String endtxt="none";
	private TextField textfield = new TextField();
	private Button okbutton = new Button("OK");
	private Button mqtt1 = new Button();
	private Button cancelbutton = new Button("Cancel");
	ComboBox<String> endpoint = new ComboBox<String>();

	@Autowired
	HttpServletRequest rec;
	String conid = "0";

	@PostConstruct
	private void init() {
		Binder<mqtt_tagtree_entity> binder = new Binder<>(); 
		Binder<tag_treeentity> binder1 = new Binder<>();  
        mqtt_tagtree_entity mqtt2 =new mqtt_tagtree_entity();  
        tag_treeentity tag =new tag_treeentity();   

        Label infoLabel = new Label();
        
		H1 hd = new H1();
		hd.addClassName("h1");
		hd.setText("Tag Editor");

		TextField tagtype, tagid, parentid, text, description, value, lowlimit, highlimit, historydeadband, mqtt;// name,

		VerticalLayout ver = new VerticalLayout();
		setAlignItems(Alignment.CENTER);
		tagtype = new TextField("Tag Type");
		//tagtype.setLabel("Tag Type");
		tagtype.setRequired(true);
		tagtype.setWidth("70%");
		tagtype.getStyle().set("background-color", "#C0C0C0");
		tagtype.setReadOnly(true);

		tagid = new TextField("Tag ID");
		tagid.setRequired(true);
		tagid.setReadOnly(true);
		tagid.getStyle().set("background-color", "#C0C0C0");
		tagid.setWidth("70%");
		List<tag_treeentity> l = tg.findAll();
		int i = 0;
		for (tag_treeentity m : l) {

			conid = m.getId().toString();

		}
		tagid.setValue("" + (Integer.parseInt(conid) + 1));
		

		parentid = new TextField("Parent ID");
		parentid.getStyle().set("background-color", "#C0C0C0");
		parentid.setWidth("70%");
		try {
			parentid.setValue(rec.getParameter("id"));
		} catch (Exception e) {
			parentid.setValue(rec.getParameter("tag_id"));
		}
		parentid.setReadOnly(true);

		text = new TextField("Text/Label");
		text.setRequired(true);
	//	text.setValueChangeMode(ValueChangeMode.EAGER);
		text.setRequiredIndicatorVisible(true);
		text.setWidth("70%");
		binder1.forField(text)
		.withValidator(new StringLengthValidator(
		"Please add the Text", 1, null)).bind(tag_treeentity :: getText,tag_treeentity :: setText);
		
		
		description = new TextField("Description");
		description.setRequired(true);
		description.setRequiredIndicatorVisible(true);
		description.setWidth("70%");
		binder.forField(description)
		.withValidator(new StringLengthValidator(
		"Please add the Description", 1, null)).bind(mqtt_tagtree_entity::getDescription, mqtt_tagtree_entity::setDescription);
			

		Select<String> enabled = new Select<String>();
		enabled.setLabel("Enabled");
		enabled.setItems("Yes", "No");
		enabled.setValue("Yes");
		enabled.setWidth("70%");

		Select<String> datatype = new Select<String>();
		datatype.setLabel("DataTypes");
		datatype.setItems("int", "float", "double", "long", "String");
		datatype.setValue("int");
		datatype.setWidth("70%");

		/*value = new TextField("Value");
		value.setRequired(true);
		value.setWidth("65%");*/

		add(ver, hd, tagtype, tagid, parentid, text, description, enabled, datatype);//, value);// name,

		HorizontalLayout hr = new HorizontalLayout();
		Label m = new Label();
		m.setWidth("70%");
		m.setText("Topic");
		mqtt = new TextField();
		mqtt.setReadOnly(true);
		mqtt.setWidth("70%");
		mqtt.setId("treeTopic");
		add(hr);
		hr.add(m, mqtt, mqtt1);
         
		VerticalLayout vr = new VerticalLayout();
		Select<String> engunit = new Select<String>();
		engunit.setLabel("Eng Unit");
		engunit.setItems("None", "Pcs", "No.", "KG", "Ton", "Gallon");// "`C", "`F",
		engunit.setValue("Pcs");
		engunit.setWidth("70%");

	/*	lowlimit = new TextField("Low Limit");
		lowlimit.setPlaceholder("0");
		lowlimit.setRequired(true);
		lowlimit.setWidth("65%");

		highlimit = new TextField("High Limit");
		highlimit.setPlaceholder("0");
		highlimit.setRequired(true);
		highlimit.setWidth("65%");*/

		add(vr, engunit);//, lowlimit, highlimit);//endpoint,   
		//add(endpoint);

		VerticalLayout vrt = new VerticalLayout();
		RadioButtonGroup<String> storehistory = new RadioButtonGroup<>();
		storehistory.setLabel("Store History");
		storehistory.setItems("No", "Yes");

		/*historydeadband = new TextField("History Deadband(In Sec.)");
		historydeadband.setPlaceholder("0");
		historydeadband.setWidth("65%");
		historydeadband.setRequired(true);
		//addendpoint);*/
		add(vrt, storehistory);// historydeadband);

		System.out.println("Hello" + req.getParameter("tag_id"));
		if (req.getParameter("tag_id") != null) {
			tag_id = Long.parseLong(req.getParameter("tag_id"));
			tag_treeentity data = tg1.get(tag_id);
			mqtt_tagtree_entity m1 = new mqtt_tagtree_entity();

			m1 = mq.getByTagID(tag_id);

			System.out.println("dasdas : " + tagtype);

			tagid.setValue(tag_id + "");
			tagtype.setValue(data.getType());
			parentid.setValue(data.getParent() + "");

			text.setValue(data.getText());
			// mqtt.setValue(m1.getMqtttopic());
			description.setValue(m1.getDescription());
			datatype.setValue(m1.getDatatype());
			enabled.setValue(m1.getEnabled());
			storehistory.setValue(m1.getStore_history());
			//value.setValue(m1.getValue());
			engunit.setValue(m1.getEng_unit());
			//lowlimit.setValue(m1.getEng_low_limit());
			//highlimit.setValue(m1.getEng_high_limit());
			//historydeadband.setValue(m1.getHistory_deadband());
			id = m1.getId();
			System.out.println("hellloooo" + data.getType());
			
			if (data.getType().equals("mqtt")) {
				for (tag_editor_mqtt_entity tm : mqtagrepo.findAll()) {
					if (tm.getTag_id().equals(req.getParameter("tag_id"))) {
						mqtt.setValue(tm.getTopic());
					}  
				}
			}
			if (data.getType().equals("modbus")) {
				for (Tag_Editor_modbus_Entity tm : modbustagrepo.findAll()) {
					if (tm.getTag_id().toString().equals(req.getParameter("tag_id"))) {
						mqtt.clear();
						mqtt.setValue(tm.getDid()+","+tm.getPerameter());
					}
				}
			}
			if (data.getType().equals("opcua")) {
				for (Tag_Editor_opcua_Entity tm : opctagrepo.findAll()) {
					System.out.println(req.getParameter("tag_id") +"  -> "+tm.getTag_id());
					if (tm.getTag_id()==Long.parseLong( req.getParameter("tag_id")) ){
						System.out.println(tm.getNodeid()+" : "+tm.getEndpoint());
						mqtt.setValue(tm.getNodeid());
						endtxt=tm.getEndpoint();
					}
				}
			}

		}
		
		System.out.println("hellloooo" + id);
		try {
			if (req.getParameter("type").contains("mqtt") || tagtype.getValue().contains("mqtt")) {
				System.out.println(req.getParameter("mqtt"));
				// mqtt1.setText("MQTT");
				s = "mqtt_tag.png";
				tagtype.setValue(req.getParameter("type"));
				mqtt1.setIcon(new Icon(VaadinIcon.EYE));
				mqtt1.addClickListener(event -> {

					UI.getCurrent().getPage().executeJavaScript(
							"window.open('mqtt_json2.html','popUpWindow','height=300,width=700,left=50,top=50,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no, status=yes');");
				});
			}

			if (req.getParameter("type").contains("modbus") || tagtype.getValue().contains("modbus")) {
				s = "modbus_tag.png";
				// mqtt1.setText("Modbus");
				tagtype.setValue(req.getParameter("type"));
				mqtt1.setIcon(new Icon(VaadinIcon.EYE));
				// mqtt1.setText("modbus");
				mqtt1.addClickListener(event -> {
					UI.getCurrent().getPage().executeJavaScript(
							"window.open('modbustree1.html','popUpWindow','height=300,width=700,left=50,top=50,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no, status=yes');");
				});
			}
			if (req.getParameter("type").contains("opcua") || tagtype.getValue().contains("opcua")) {

				s = "opc_tag.png";
				List<ConnectionInfo> c = opcConn.findAll();
				Collection<String> tr=new ArrayList<String>();
				for (ConnectionInfo coni : c) {
					
					tr.add(coni.getEndpointUrl());
					System.out.println(coni.getEndpointUrl());
					endpoint.setItems(tr);
				}
				
				endpoint.setLabel("Endpoint URL");
				endpoint.setWidth("70%");
				endpoint.setValue(endtxt);
			//	mqtt1.setText("OPCUA");
				tagtype.setValue(req.getParameter("type"));
				mqtt1.setIcon(new Icon(VaadinIcon.EYE));


				mqtt1.addClickListener(event -> {
					System.out.println(endpoint.getValue().toString());
					UI.getCurrent().getPage().executeJavaScript("window.open('tree2.html?url="
							+ endpoint.getValue().toString()
							+ "','popUpWindow','height=300,width=700,left=50,top=50,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no, status=yes');");
				});
				add(endpoint);
				
			}
		} catch (NullPointerException e) {
			if (tagtype.getValue().contains("mqtt")) {
				System.out.println(req.getParameter("mqtt"));
				// mqtt1.setText("MQTT");
				s = "mqtt_tag.png";
				// tagtype.setValue(req.getParameter("type"));
				mqtt1.setIcon(new Icon(VaadinIcon.EYE));
				mqtt1.addClickListener(event -> {

					UI.getCurrent().getPage().executeJavaScript(
		 					"window.open('mqtt_json2.html','popUpWindow','height=300,width=700,left=50,top=50,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no, status=yes');");
				});
			}  
  
			if (tagtype.getValue().contains("modbus")) {
				s = "modbus_tag.png";
				// mqtt1.setText("Modbus");
				// tagtype.setValue(req.getParameter("type"));
				mqtt1.setIcon(new Icon(VaadinIcon.EYE));
				// mqtt1.setText("modbus");
				mqtt1.addClickListener(event -> {
					UI.getCurrent().getPage().executeJavaScript(
							"window.open('modbustree1.html','popUpWindow','height=300,width=700,left=50,top=50,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no, status=yes');");
				});
			}
			if (tagtype.getValue().contains("opcua")) {

				s = "opc_tag.png";
				List<ConnectionInfo> c = opcConn.findAll();
				for (ConnectionInfo coni : c) {
					endpoint.setItems(coni.getEndpointUrl());
				}
				VerticalLayout vr1 =new VerticalLayout();
 				endpoint.setLabel("Endpoint URL");
				endpoint.setWidth("70%");
				endpoint.setValue(endtxt);
			//	mqtt1.setText("OPCUA");
				// tagtype.setValue(req.getParameter("type"));
				mqtt1.setIcon(new Icon(VaadinIcon.EYE));

				mqtt1.addClickListener(event -> {
					System.out.println(endpoint.getValue().toString());
					UI.getCurrent().getPage().executeJavaScript("window.open('tree2.html?url="
							+ endpoint.getValue().toString()
							+ "','popUpWindow','height=300,width=700,left=50,top=50,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no, status=yes');");
				});
				add(endpoint);//endpoint
			}
		}
  
		//System.out.println("hellloooo" + id);
		HorizontalLayout hor = new HorizontalLayout();
		okbutton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
		okbutton.addClassName("button1");
		okbutton.setWidth("70%");
		okbutton.addClickListener(event -> {
		//	Notification.show("hihih");
			//System.out.println("hellloooo" + id);
			Notification.show("Hellooo connection is done");
			if (binder.writeBeanIfValid(mqtt2)) {
				Notification.show("Hellooo cnnncnn"+mqtt2);
				//infoLabel.setText("Saved bean values: " + mqtt2);
				UI.getCurrent().getPage().executeJavaScript("var s=document.getElementById('treeTopic').value; alert(s); window.open('/save1?mqtt='+s+'&id='+"+tagid.getValue()+"+'&description="+description.getValue()+"&datatype="+datatype.getValue()+"&enabled="+enabled.getValue()+"&storehistory="+storehistory.getValue()+"&engunit="+engunit.getValue()+"&text="+text.getValue()+"&tagtype="+tagtype.getValue()+"&parentid="+parentid.getValue()+"&tagid="+tagid.getValue()+"&icon="+s+ "&idm=" + id + "', \"_self\");");
		 		UI.getCurrent().getPage().executeJavaScript("window.parent.location.reload();");

				}
			else {
				BinderValidationStatus<mqtt_tagtree_entity> validate = binder.validate();
				String errorText = validate.getFieldValidationStatuses()
				.stream().filter(BindingValidationStatus::isError)
				.map(BindingValidationStatus::getMessage)
				.map(Optional::get).distinct()
				.collect(Collectors.joining(", "));
				infoLabel.setText("There are errors: " + errorText);
				}
			 if (binder1.writeBeanIfValid(tag)) {
				Notification.show("Hellooo cnnncnn"+tag);
				//UI.getCurrent().getPage().executeJavaScript("var s=document.getElementById('treeTopic').value; alert(s); window.open('/save1?mqtt='+s+'&id='+"+tagid.getValue()+"+'&description="+description.getValue()+"&datatype="+datatype.getValue()+"&enabled="+enabled.getValue()+"&storehistory="+storehistory.getValue()+"&engunit="+engunit.getValue()+"&text="+text.getValue()+"&tagtype="+tagtype.getValue()+"&parentid="+parentid.getValue()+"&tagid="+tagid.getValue()+"&icon="+s+ "&idm=" + id + "', \"_self\");");
				//UI.getCurrent().getPage().executeJavaScript("window.parent.location.reload();");

				//infoLabel.setText("Saved bean values: " + tag);
				} else {
				BinderValidationStatus<tag_treeentity> validate = binder1.validate();
				String errorText = validate.getFieldValidationStatuses()
				.stream().filter(BindingValidationStatus::isError)
				.map(BindingValidationStatus::getMessage)
				.map(Optional::get).distinct()
				.collect(Collectors.joining(", "));
				infoLabel.setText("There are errors: " + errorText);
				}
			*/
			
			if(tagtype.getValue().contains("opcua"))
			{
				
			//UI.getCurrent().getPage().executeJavaScript("var s=document.getElementById('treeTopic').value;  window.open('/test?mqtt='+s+'&id='+"+tagid.getValue()+"+'&description="+description.getValue()+"&datatype="+datatype.getValue()+"&enabled="+enabled.getValue()+"&storehistory="+storehistory.getValue()+"&historydeadband="+historydeadband.getValue()+"&value="+value.getValue()+"&engunit="+engunit.getValue()+"&lowlimit="+lowlimit.getValue()+"&highlimit="+highlimit.getValue()+"&text="+text.getValue()+"&tagtype="+tagtype.getValue()+"&parentid="+parentid.getValue()+"&tagid="+tagid.getValue()+"&icon="+s+"&endpoint="+endpoint.getValue()+ "&idm=" + id + "', \"_self\");");
//				try {
				//UI.getCurrent().getPage().executeJavaScript("var s=document.getElementById('treeTopic').value;  window.open('/subscribeNode?&url="+endpoint.getValue()+"&id=0&name='+s, \"_self\");");
			UI.getCurrent().getPage().executeJavaScript("var s=document.getElementById('treeTopic').value;  window.open('/save1?mqtt='+s+'&id='+"+tagid.getValue()+"+'&description="+description.getValue()+"&datatype="+datatype.getValue()+"&enabled="+enabled.getValue()+"&storehistory="+storehistory.getValue()+"&engunit="+engunit.getValue()+"&text="+text.getValue()+"&tagtype="+tagtype.getValue()+"&parentid="+parentid.getValue()+"&tagid="+tagid.getValue()+"&icon="+s+"&endpoint="+endpoint.getValue()+ "&idm=" + id + "', \"_blank\");window.open('/subscribeNode?&url="+endpoint.getValue()+"&id=0&name='+s, \"_self\");");
				
			UI.getCurrent().getPage().executeJavaScript("window.parent.location.reload();");
				
			}
			else{
				UI.getCurrent().getPage().executeJavaScript("var s=document.getElementById('treeTopic').value; alert(s); window.open('/save1?mqtt='+s+'&id='+"+tagid.getValue()+"+'&description="+description.getValue()+"&datatype="+datatype.getValue()+"&enabled="+enabled.getValue()+"&storehistory="+storehistory.getValue()+"&engunit="+engunit.getValue()+"&text="+text.getValue()+"&tagtype="+tagtype.getValue()+"&parentid="+parentid.getValue()+"&tagid="+tagid.getValue()+"&icon="+s+ "&idm=" + id + "', \"_self\");");
				UI.getCurrent().getPage().executeJavaScript("window.parent.location.reload();");
			
			}
			
			
						  
		});

		cancelbutton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
		cancelbutton.addClassName("button1");
		cancelbutton.setWidth("70%");
		cancelbutton.addClickListener(event -> {
			Notification.show("hihih");
			UI.getCurrent().getPage().executeJavaScript("window.parent.location.reload();");

		});        

		addClassName("form");
		
		add(hor);
		hor.add(okbutton, cancelbutton);
		// add(mqtt1,hd,tagtype,tagid,parentid,name,text,description,enabled,datatype,value,engunit,lowlimit,highlimit,storehistory,historydeadband,okbutton);
	}

}
