﻿/*
 *  TOPPERS/ECNL Prototyping tool
 *
 *  Copyright (C) 2017 Cores Co., Ltd. Japan
 *
 *  上記著作権者は，以下の(1)～(4)の条件を満たす場合に限り，本ソフトウェ
 *  ア（本ソフトウェアを改変したものを含む．以下同じ）を使用・複製・改
 *  変・再配布（以下，利用と呼ぶ）することを無償で許諾する．
 *  (1) 本ソフトウェアをソースコードの形で利用する場合には，上記の著作
 *      権表示，この利用条件および下記の無保証規定が，そのままの形でソー
 *      スコード中に含まれていること．
 *  (2) 本ソフトウェアを，ライブラリ形式など，他のソフトウェア開発に使
 *      用できる形で再配布する場合には，再配布に伴うドキュメント（利用
 *      者マニュアルなど）に，上記の著作権表示，この利用条件および下記
 *      の無保証規定を掲載すること．
 *  (3) 本ソフトウェアを，機器に組み込むなど，他のソフトウェア開発に使
 *      用できない形で再配布する場合には，次のいずれかの条件を満たすこ
 *      と．
 *    (a) 再配布に伴うドキュメント（利用者マニュアルなど）に，上記の著
 *        作権表示，この利用条件および下記の無保証規定を掲載すること．
 *    (b) 再配布の形態を，別に定める方法によって，TOPPERSプロジェクトに
 *        報告すること．
 *  (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
 *      害からも，上記著作権者およびTOPPERSプロジェクトを免責すること．
 *      また，本ソフトウェアのユーザまたはエンドユーザからのいかなる理
 *      由に基づく請求からも，上記著作権者およびTOPPERSプロジェクトを
 *      免責すること．
 *
 *  本ソフトウェアは，無保証で提供されているものである．上記著作権者お
 *  よびTOPPERSプロジェクトは，本ソフトウェアに関して，特定の使用目的
 *  に対する適合性も含めて，いかなる保証も行わない．また，本ソフトウェ
 *  アの利用により直接的または間接的に生じたいかなる損害に関しても，そ
 *  の責任を負わない．
 *
 *  @(#) $Id$
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Bridge;
using Bridge.Html5;
using Bridge.jQuery2;

namespace WebMrbc
{
	internal class EObjectWorkspace : IClassWorkspace
	{
		public JsonObjectInfo eobject;
		private Workspace workspace;
		BlocklyView view;
		Action<bool> callback;
		protected Ruby _RubyCode;

		public string Identifier { get { return view.Identifier; } }
		public Workspace Workspace { get { return workspace; } }
		public BlocklyView View { get { return view; } }
		public Ruby RubyCode { get { return _RubyCode; } }

		public EObjectWorkspace(BlocklyView view, JsonObjectInfo eobject)
		{
			this.view = view;
			this.eobject = eobject;
			workspace = view.Init();

			view.FlyoutCategoryHandlers.Add("ECHONET_LITE_PROPERTY", FlyoutCategory);

			UpdateInitialBlock();
		}

		protected void UpdateInitialBlock()
		{
			var blocks = Workspace.getTopBlocks(false);
			foreach (var b in blocks) {
				if ((b.type == ENodeInitializeBlock.type_name)
					|| (b.type == EObjectInitializeBlock.type_name)) {
					b.dispose(false);
					continue;
				}

				if ((b.type == EPropertyFixLenBlock.type_name)
					|| (b.type == EPropertyVarLenBlock.type_name)) {
					((dynamic)b).InitPropertyInfo(this);
					continue;
				}
			}

			var xml = Document.CreateElement("xml");
			var block = Document.CreateElement("block");
			xml.AppendChild(block);

			if ((eobject.type.classGroup.classGroupCode == 0x0E)
				 && (eobject.type.classCode == 0xF0))
				block.SetAttribute("type", ENodeInitializeBlock.type_name);
			else
				block.SetAttribute("type", EObjectInitializeBlock.type_name);

			var statement = Document.CreateElement("statement");
			statement.SetAttribute("name", "DO");
			block.AppendChild(statement);

			var prev = (Element)null;
			foreach (var pi in eobject.properties) {
				if (CodeGenerator.IsExtractProperty(pi))
					continue;

				var vset = Document.CreateElement("block");
				vset.SetAttribute("type", "variables_set");

				var field = Document.CreateElement("field");
				field.SetAttribute("name", "VAR");
				field.AppendChild(Document.CreateTextNode(CodeGenerator.GetPropertyIdentifier(pi)));
				vset.AppendChild(field);

				var value = Document.CreateElement("value");
				value.SetAttribute("name", "VALUE");
				vset.AppendChild(value);

				var text = Document.CreateElement("shadow");
				text.SetAttribute("type", "text");
				value.AppendChild(text);

				field = Document.CreateElement("field");
				field.SetAttribute("name", "TEXT");
				var body = new StringBuilder();
				GetInitialValue(body, pi, pi.valueDescription, false);
				field.AppendChild(Document.CreateTextNode(body.ToString()));
				text.AppendChild(field);

				if (prev != null) {
					var next = Document.CreateElement("next");
					next.AppendChild(vset);
					prev.AppendChild(next);
				}
				else {
					statement.AppendChild(vset);
				}
				prev = vset;
			}

			Blockly.Xml.domToWorkspace(xml, Workspace);
		}

		private void GetInitialValue(StringBuilder body, JsonFieldInfo emi, string valRng, bool recursive)
		{
			if (emi.type == "manufacturer_code_t") {
				body.Append("#{$MAKER_CODE}");
				return;
			}

			if (emi.type == "version_information_t") {
				body.Append("\\x01\\x0A\\x01\\x00");
				return;
			}

			if (emi.type == "standard_version_information_t") {
				body.Append("\\x00\\x00C\\x00");
				return;
			}

			if (emi.primitive) {
				int count = emi.arrayCount;
				if (count == 0) {
					body.Append(CodeGenerator.GetInitialValue(valRng, emi));
				}
				else {
					body.Append("");
					for (int i = 0; i < count; i++) {
						body.Append(CodeGenerator.GetInitialValue(valRng, emi));
					}
					body.Append("");
				}
			}
			else if (emi.fields != null && emi.fields.Length > 0) {
				foreach (var efi in emi.fields) {
					GetInitialValue(body, efi, efi.valueDescription, true);
				}
			}
		}

		public virtual string GetImageUrl()
		{
			return "img/no_image.png";
		}

		public virtual bool IsPreset()
		{
			return false;
		}

		public virtual string ToCode(string filename)
		{
			if (eobject == null)
				return "";

			_RubyCode = new Ruby(filename);
			_RubyCode.init(Workspace);
			var result = _RubyCode.defineEObject(eobject, workspace);
			view.Changed = false;
			return result;
		}

		//Element ele;

		public virtual void Activate()
		{
			//ele = Blockly.Xml.workspaceToDom(workspace);
		}

		public virtual void Inactivate()
		{
			//workspace.clear();
			//Blockly.Xml.domToWorkspace(ele, workspace);
		}

		public void ReloadToolbox(HTMLElement toolbox)
		{
			toolbox.AppendChild(Document.CreateElement("sep"));
			var xml = jQuery.ParseXML(App.ArduinoToolbox);
			var categories = xml.ChildNodes[0];
			foreach (var item in categories.ChildNodes) {
				if (item.NodeName != "category")
					continue;
				toolbox.AppendChild(item);
			}

			toolbox.AppendChild(Document.CreateElement("sep"));
			xml = jQuery.ParseXML(App.EcnlToolbox);
			categories = xml.ChildNodes[0];
			foreach (var item in categories.ChildNodes) {
				if (item.NodeName != "category")
					continue;
				toolbox.AppendChild(item);
			}

			var category = Document.CreateElement("category");
			category.SetAttribute("name", "ECHONET Lite Property");
			category.SetAttribute("custom", "ECHONET_LITE_PROPERTY");
			category.SetAttribute("colour", "230");
			toolbox.AppendChild(category);
		}

		public EPropertyBlock[] allEProperties(Workspace root)
		{
			var blocks = root.getAllBlocks();
			var eproperties = new EPropertyBlock[0];
			for (var i = 0; i < blocks.Length; i++) {
				var b = blocks[i];
				if ((b.type == EPropertyFixLenBlock.type_name)
					|| (b.type == EPropertyVarLenBlock.type_name)) {
					eproperties.Push(b);
				}
			}
			return eproperties;
		}

		private int procTupleComparator_(Tuple<string, byte, bool> ta, Tuple<string, byte, bool> tb)
		{
			return ta.Item2 - tb.Item2;
		}

		private Element[] FlyoutCategory(Workspace workspace)
		{
			var xmlList = new Element[0];
			var properties = allEProperties(workspace);

			foreach (var pi in eobject.properties) {
				if (CodeGenerator.IsExtractProperty(pi))
					continue;

				bool exist = false;
				foreach (var p in from p in properties where p.PropertyCode == pi.propertyCode select p) {
					exist = true;
					break;
				}
				if (exist)
					continue;

				bool varlen = pi.access.Contains("VARIABLE");
				string identifier = CodeGenerator.GetPropertyIdentifier(pi);
				ValueRange valueRange;
				if (!CodeGenerator.HasPropSetter(pi, out valueRange))
					valueRange = null;

				var block = Document.CreateElement("block");
				if (varlen)
					block.SetAttribute("type", EPropertyVarLenBlock.type_name);
				else
					block.SetAttribute("type", EPropertyFixLenBlock.type_name);

				var field = Document.CreateElement("field");
				field.SetAttribute("name", "IDENTIFIER");
				field.AppendChild(Document.CreateTextNode(identifier));
				block.AppendChild(field);

				field = Document.CreateElement("field");
				field.SetAttribute("name", "DESCRIPTION");
				field.AppendChild(Document.CreateTextNode(pi.description));
				block.AppendChild(field);

				field = Document.CreateElement("field");
				field.SetAttribute("name", "PROPERTY_CODE");
				field.AppendChild(Document.CreateTextNode(pi.propertyCode.ToString("X2")));
				block.AppendChild(field);

				field = Document.CreateElement("field");
				field.SetAttribute("name", "PROPERTY_SIZE");
				field.AppendChild(Document.CreateTextNode(pi.size.ToString()));
				block.AppendChild(field);

				xmlList.Push(block);

				// プロパティが可変長の場合
				if (varlen) {
					{
						var statement = Document.CreateElement("statement");
						statement.SetAttribute("name", "SET");
						block.AppendChild(statement);

						var ifBlock = CreateSizeCheckBlocks();
						statement.AppendChild(ifBlock);

						var next = Document.CreateElement("next");
						ifBlock.AppendChild(next);

						if (pi.access.Contains("ANNOUNCE")) {
							Element annoBlock = CreateAnnoCheck();
							next.AppendChild(annoBlock);

							next = Document.CreateElement("next");
							annoBlock.AppendChild(next);
						}

						Element setBlock = null;
						if (valueRange != null) {
							setBlock = CreateSetStatement(valueRange);
						}
						else {
							setBlock = Document.CreateElement("block");
							setBlock.SetAttribute("type", EcnlSaveReceivedPropertyBlock.type_name);
						}

						if (setBlock != null) {
							next.AppendChild(setBlock);
						}
					}

					{
						var value = Document.CreateElement("value");
						value.SetAttribute("name", "SET_RET");
						block.AppendChild(value);

						var subblock = Document.CreateElement("block");
						subblock.SetAttribute("type", EcnlGetPropertyInfoBlock.type_name);
						value.AppendChild(subblock);

						field = Document.CreateElement("field");
						field.SetAttribute("name", "MEMBER");
						field.AppendChild(Document.CreateTextNode("sz"));
						subblock.AppendChild(field);
					}
				}
				// プロパティが固定長の場合
				else if ((valueRange == null) || ((valueRange.Values.Length == 0) && (valueRange.Ranges.Length == 0))) {
					var mutation = Document.CreateElement("mutation");
					mutation.SetAttribute("property_code", pi.propertyCode.ToString("X2"));
					mutation.SetAttribute("identifier", identifier);
					mutation.SetAttribute("description", pi.description);
					mutation.SetAttribute("property_size", pi.size.ToString());
					mutation.SetAttribute("default", "1");
					mutation.SetAttribute("user_getter", "1");
					block.AppendChild(mutation);

					Element setBlock = null;
					switch (pi.propertyCode) {
					// 現在時刻
					case 0x97:
						setBlock = CreateSetTime();
						break;
					// 現在日付
					case 0x98:
						setBlock = CreateSetDate();
						break;
					default:
						setBlock = Document.CreateElement("block");
						setBlock.SetAttribute("type", EcnlSaveReceivedPropertyBlock.type_name);
						break;
					}

					if (setBlock != null) {
						var statement = Document.CreateElement("statement");
						statement.SetAttribute("name", "DEFAULT_SET");
						block.AppendChild(statement);

						statement.AppendChild(setBlock);
					}
				}
				else {
					var mutation = Document.CreateElement("mutation");
					mutation.SetAttribute("property_code", pi.propertyCode.ToString("X2"));
					mutation.SetAttribute("identifier", identifier);
					mutation.SetAttribute("description", pi.description);
					mutation.SetAttribute("property_size", pi.size.ToString());
					mutation.SetAttribute("default", "0");
					mutation.SetAttribute("user_getter", "1");
					block.AppendChild(mutation);

					int i = 0;
					foreach (var v in valueRange.Values) {
						var branch = Document.CreateElement("case");
						branch.SetAttribute("value", v.Val.ToString());
						branch.AppendChild(Document.CreateTextNode(v.Disp.ToString()));
						mutation.AppendChild(branch);

						field = Document.CreateElement("field");
						field.SetAttribute("name", "CASE_DESCRIPTION" + i);
						field.AppendChild(Document.CreateTextNode(v.Disp.ToString()));
						block.AppendChild(field);

						field = Document.CreateElement("field");
						field.SetAttribute("name", "CASE_VALUE" + i);
						field.AppendChild(Document.CreateTextNode(v.Val.ToString()));
						block.AppendChild(field);

						var statement = Document.CreateElement("statement");
						statement.SetAttribute("name", "SET" + i);
						block.AppendChild(statement);

						var setBlock = Document.CreateElement("shadow");
						setBlock.SetAttribute("type", EcnlSaveReceivedPropertyBlock.type_name);
						statement.AppendChild(setBlock);

						i++;
					}

					foreach (var v in valueRange.Ranges) {
						var branch = Document.CreateElement("case");
						branch.SetAttribute("minimum", v.Min.ToString());
						branch.SetAttribute("maximum", v.Max.ToString());
						branch.AppendChild(Document.CreateTextNode(v.Disp.ToString()));
						mutation.AppendChild(branch);

						field = Document.CreateElement("field");
						field.SetAttribute("name", "CASE_DESCRIPTION" + i);
						field.AppendChild(Document.CreateTextNode(v.Disp.ToString()));
						block.AppendChild(field);

						field = Document.CreateElement("field");
						field.SetAttribute("name", "CASE_MIN" + i);
						field.AppendChild(Document.CreateTextNode(v.Min.ToString()));
						block.AppendChild(field);

						field = Document.CreateElement("field");
						field.SetAttribute("name", "CASE_MAX" + i);
						field.AppendChild(Document.CreateTextNode(v.Max.ToString()));
						block.AppendChild(field);

						var statement = Document.CreateElement("statement");
						statement.SetAttribute("name", "SET" + i);
						block.AppendChild(statement);

						var setBlock = Document.CreateElement("shadow");
						setBlock.SetAttribute("type", EcnlSaveReceivedPropertyBlock.type_name);
						statement.AppendChild(setBlock);

						i++;
					}
				}

				{
					var statement = Document.CreateElement("statement");
					statement.SetAttribute("name", "GET");
					block.AppendChild(statement);

					Element ifBlock = null;
					if (varlen) {
						ifBlock = CreateSizeCheckBlocks();
						statement.AppendChild(ifBlock);
					}

					Element getBlock = null;
					switch (pi.propertyCode) {
					// 現在時刻
					case 0x97:
						getBlock = CreateGetTime(identifier);
						break;
					// 現在日付
					case 0x98:
						getBlock = CreateGetDate(identifier);
						break;
					default:
						break;
					}

					if (getBlock != null) {
						if (ifBlock != null) {
							var next = Document.CreateElement("next");
							next.AppendChild(getBlock);

							ifBlock.AppendChild(next);
						}
						else {
							statement.AppendChild(getBlock);
						}
					}
				}

				{
					var value = Document.CreateElement("value");
					value.SetAttribute("name", "GET_RET");
					block.AppendChild(value);

					Element subblock = null;
					switch (pi.propertyCode) {
					// 現在時刻
					case 0x97:
						subblock = CreateGetRetTime(identifier);
						break;
					// 現在日付
					case 0x98:
						subblock = CreateGetRetDate(identifier);
						break;
					default:
						subblock = Document.CreateElement("block");
						subblock.SetAttribute("type", EcnlGetSavedPropertyBlock.type_name);
						break;
					}

					if (subblock != null) {
						value.AppendChild(subblock);
					}
				}
			}

			return xmlList;
		}

		private Element CreateSetDate()
		{
			var localvar = "date";
			var setBlock = CreateGetDateTimeBlock(localvar);

			var next = Document.CreateElement("next");
			setBlock.AppendChild(next);

			var rtcBlock = CreateSetDateTimeItemBlock(localvar, "0", "SHORT", 0);
			next.AppendChild(rtcBlock);

			next = Document.CreateElement("next");
			rtcBlock.AppendChild(next);

			rtcBlock = CreateSetDateTimeItemBlock(localvar, "1", "BYTE", 2);
			next.AppendChild(rtcBlock);

			next = Document.CreateElement("next");
			rtcBlock.AppendChild(next);

			rtcBlock = CreateSetDateTimeItemBlock(localvar, "2", "BYTE", 3);
			next.AppendChild(rtcBlock);

			next = Document.CreateElement("next");
			rtcBlock.AppendChild(next);

			var callBlock = CreateSetDateTimeBlock(localvar);
			next.AppendChild(callBlock);

			return setBlock;
		}

		private Element CreateGetDate(string name)
		{
			return CreateGetDateTimeBlock(name);
		}

		private Element CreateGetRetDate(string name)
		{
			var subBlock = Document.CreateElement("block");
			subBlock.SetAttribute("type", DataJoinBlock.type_name);

			var mutation = Document.CreateElement("mutation");
			mutation.SetAttribute("items", "3");
			subBlock.AppendChild(mutation);

			var value = Document.CreateElement("value");
			value.SetAttribute("name", "ADD0");
			subBlock.AppendChild(value);

			var rtcBlock = CreateGetDateTimeBlock(name, "0");
			value.AppendChild(rtcBlock);

			value = Document.CreateElement("value");
			value.SetAttribute("name", "ADD1");
			subBlock.AppendChild(value);

			rtcBlock = CreateGetDateTimeBlock(name, "1");
			value.AppendChild(rtcBlock);

			value = Document.CreateElement("value");
			value.SetAttribute("name", "ADD2");
			subBlock.AppendChild(value);

			rtcBlock = CreateGetDateTimeBlock(name, "2");
			value.AppendChild(rtcBlock);

			return subBlock;
		}

		private Element CreateSetTime()
		{
			var localvar = "time";
			var setBlock = CreateGetDateTimeBlock(localvar);

			var next = Document.CreateElement("next");
			setBlock.AppendChild(next);

			var rtcBlock = CreateSetDateTimeItemBlock(localvar, "3", "BYTE", 0);
			next.AppendChild(rtcBlock);

			next = Document.CreateElement("next");
			rtcBlock.AppendChild(next);

			rtcBlock = CreateSetDateTimeItemBlock(localvar, "4", "BYTE", 1);
			next.AppendChild(rtcBlock);

			next = Document.CreateElement("next");
			rtcBlock.AppendChild(next);

			var callBlock = CreateSetDateTimeBlock(localvar);
			next.AppendChild(callBlock);

			return setBlock;
		}

		private Element CreateGetTime(string name)
		{
			return CreateGetDateTimeBlock(name);
		}

		private Element CreateGetRetTime(string name)
		{
			var subBlock = Document.CreateElement("block");
			subBlock.SetAttribute("type", DataJoinBlock.type_name);

			var mutation = Document.CreateElement("mutation");
			mutation.SetAttribute("items", "2");
			subBlock.AppendChild(mutation);

			var value = Document.CreateElement("value");
			value.SetAttribute("name", "ADD0");
			subBlock.AppendChild(value);

			var rtcBlock = CreateGetDateTimeBlock(name, "3");
			value.AppendChild(rtcBlock);

			value = Document.CreateElement("value");
			value.SetAttribute("name", "ADD1");
			subBlock.AppendChild(value);

			rtcBlock = CreateGetDateTimeBlock(name, "4");
			value.AppendChild(rtcBlock);

			return subBlock;
		}

		private Element CreateGetDateTimeBlock(string name, string item)
		{
			var rtcBlock = Document.CreateElement("block");
			rtcBlock.SetAttribute("type", RtcDateTimeItemBlock.type_name);

			var field = Document.CreateElement("field");
			field.SetAttribute("name", "ARRAY");
			field.AppendChild(Document.CreateTextNode(name));
			rtcBlock.AppendChild(field);

			field = Document.CreateElement("field");
			field.SetAttribute("name", "ITEM");
			field.AppendChild(Document.CreateTextNode(item));
			rtcBlock.AppendChild(field);

			return rtcBlock;
		}

		private Element CreateGetDateTimeBlock(string name)
		{
			var block = Document.CreateElement("block");
			block.SetAttribute("type", VariablesSetBlock.type_name);

			var field = Document.CreateElement("field");
			field.SetAttribute("name", "VAR");
			field.AppendChild(Document.CreateTextNode(name));
			block.AppendChild(field);

			var value = Document.CreateElement("value");
			value.SetAttribute("name", "VALUE");
			block.AppendChild(value);

			var rtcBlock = Document.CreateElement("block");
			rtcBlock.SetAttribute("type", RtcGetTimeBlock.type_name);
			value.AppendChild(rtcBlock);

			return block;
		}

		private Element CreateSetDateTimeBlock(string localvar)
		{
			var callBlock = Document.CreateElement("block");
			callBlock.SetAttribute("type", CallBlock.type_name);

			var value = Document.CreateElement("value");
			value.SetAttribute("name", "RET");
			callBlock.AppendChild(value);

			var rtcBlock = Document.CreateElement("block");
			rtcBlock.SetAttribute("type", RtcSettimeBlock.type_name);
			value.AppendChild(rtcBlock);

			value = Document.CreateElement("value");
			value.SetAttribute("name", "DATE");
			rtcBlock.AppendChild(value);

			var vgetBlock = Document.CreateElement("block");
			vgetBlock.SetAttribute("type", VariablesGetBlock.type_name);
			value.AppendChild(vgetBlock);

			var field = Document.CreateElement("field");
			field.SetAttribute("name", "VAR");
			field.AppendChild(Document.CreateTextNode(localvar));
			vgetBlock.AppendChild(field);

			return callBlock;
		}

		private Element CreateSetDateTimeItemBlock(string localvar, string item, string width, int pos)
		{
			var rtcBlock = Document.CreateElement("block");
			rtcBlock.SetAttribute("type", RtcSetDateTimeItemBlock.type_name);

			var field = Document.CreateElement("field");
			field.SetAttribute("name", "ARRAY");
			field.AppendChild(Document.CreateTextNode(localvar));
			rtcBlock.AppendChild(field);

			field = Document.CreateElement("field");
			field.SetAttribute("name", "ITEM");
			field.AppendChild(Document.CreateTextNode(item));
			rtcBlock.AppendChild(field);

			var value = Document.CreateElement("value");
			value.SetAttribute("name", "VALUE");
			rtcBlock.AppendChild(value);

			var dataBlock = CreateReceivedData(width, pos);
			value.AppendChild(dataBlock);

			return rtcBlock;
		}

		private Element CreateAnnoCheck()
		{
			var annoBlock = Document.CreateElement("block");
			annoBlock.SetAttribute("type", EcnlSetAnnounceRequestBlock.type_name);

			var value = Document.CreateElement("value");
			value.SetAttribute("name", "DATA");
			annoBlock.AppendChild(value);

			var subblock = Document.CreateElement("block");
			subblock.SetAttribute("type", EcnlGetSavedPropertyBlock.type_name);
			value.AppendChild(subblock);
			return annoBlock;
		}

		private Element CreateSizeCheckBlocks()
		{
			Element field;
			var ifBlock = Document.CreateElement("block");
			ifBlock.SetAttribute("type", ControlsIfBlock.type_name);

			var value = Document.CreateElement("value");
			value.SetAttribute("name", "IF0");
			ifBlock.AppendChild(value);

			var compBlock = Document.CreateElement("block");
			compBlock.SetAttribute("type", LogicCompareBlock.type_name);
			value.AppendChild(compBlock);

			field = Document.CreateElement("field");
			field.SetAttribute("name", "OP");
			field.AppendChild(Document.CreateTextNode("NEQ"));
			compBlock.AppendChild(field);

			value = Document.CreateElement("value");
			value.SetAttribute("name", "A");
			compBlock.AppendChild(value);

			var subblock = Document.CreateElement("block");
			subblock.SetAttribute("type", EcnlReceivedDataSizeBlock.type_name);
			value.AppendChild(subblock);

			value = Document.CreateElement("value");
			value.SetAttribute("name", "B");
			compBlock.AppendChild(value);

			subblock = Document.CreateElement("block");
			subblock.SetAttribute("type", EcnlGetPropertyInfoBlock.type_name);
			value.AppendChild(subblock);

			field = Document.CreateElement("field");
			field.SetAttribute("name", "MEMBER");
			field.AppendChild(Document.CreateTextNode("sz"));
			subblock.AppendChild(field);

			var doStatement = Document.CreateElement("statement");
			doStatement.SetAttribute("name", "DO0");
			ifBlock.AppendChild(doStatement);

			subblock = Document.CreateElement("block");
			subblock.SetAttribute("type", EcnlNoOpBlock.type_name);
			doStatement.AppendChild(subblock);

			return ifBlock;
		}

		private Element CreateSetStatement(ValueRange valueRange)
		{
			Element field;

			var block = Document.CreateElement("block");
			block.SetAttribute("type", SwitchCaseNumberBlock.type_name);

			var mutation = Document.CreateElement("mutation");
			mutation.SetAttribute("default", "1");
			block.AppendChild(mutation);

			int i = 0;
			foreach (var v in valueRange.Values) {
				var branch = Document.CreateElement("case");
				branch.SetAttribute("value", v.Val.ToString());
				branch.AppendChild(Document.CreateTextNode(v.Disp.ToString()));
				mutation.AppendChild(branch);

				field = Document.CreateElement("field");
				field.SetAttribute("name", "DESCRIPTION" + i);
				field.AppendChild(Document.CreateTextNode(v.Disp.ToString()));
				block.AppendChild(field);

				field = Document.CreateElement("field");
				field.SetAttribute("name", "CONST" + i);
				field.AppendChild(Document.CreateTextNode(v.Val.ToString()));
				block.AppendChild(field);
				i++;
			}

			foreach (var v in valueRange.Ranges) {
				var branch = Document.CreateElement("case");
				branch.SetAttribute("minimum", v.Min.ToString());
				branch.SetAttribute("maximum", v.Max.ToString());
				branch.AppendChild(Document.CreateTextNode(v.Disp.ToString()));
				mutation.AppendChild(branch);

				field = Document.CreateElement("field");
				field.SetAttribute("name", "DESCRIPTION" + i);
				field.AppendChild(Document.CreateTextNode(v.Disp.ToString()));
				block.AppendChild(field);

				field = Document.CreateElement("field");
				field.SetAttribute("name", "RANGE_MIN" + i);
				field.AppendChild(Document.CreateTextNode(v.Min.ToString()));
				block.AppendChild(field);

				field = Document.CreateElement("field");
				field.SetAttribute("name", "RANGE_MAX" + i);
				field.AppendChild(Document.CreateTextNode(v.Max.ToString()));
				block.AppendChild(field);
				i++;
			}

			return block;
		}

		private Element CreateReceivedData(string width, int pos)
		{
			var block = Document.CreateElement("block");
			block.SetAttribute("type", EcnlDataToNumberBlock.type_name);

			var field = Document.CreateElement("field");
			field.SetAttribute("name", "WIDTH");
			field.AppendChild(Document.CreateTextNode(width));
			block.AppendChild(field);

			var value = Document.CreateElement("value");
			value.SetAttribute("name", "POSITION");
			block.AppendChild(value);

			var subBlock = Document.CreateElement("shadow");
			subBlock.SetAttribute("type", MathNumberBlock.type_name);
			value.AppendChild(subBlock);

			field = Document.CreateElement("field");
			field.SetAttribute("name", "NUM");
			field.AppendChild(Document.CreateTextNode(pos.ToString()));
			subBlock.AppendChild(field);

			return block;
		}

		private Element RengeCheack(string width, int pos, long min, long max)
		{
			var block2 = Document.CreateElement("block");
			block2.SetAttribute("type", LogicOperationBlock.type_name);

			var field = Document.CreateElement("field");
			field.SetAttribute("name", "OP");
			field.AppendChild(Document.CreateTextNode("AND"));
			block2.AppendChild(field);

			var value = Document.CreateElement("value");
			value.SetAttribute("name", "A");
			block2.AppendChild(value);

			var a = CompareNum(width, pos, "GTE", min);
			value.AppendChild(a);

			value = Document.CreateElement("value");
			value.SetAttribute("name", "B");
			block2.AppendChild(value);

			var b = CompareNum(width, pos, "LTE", max);
			value.AppendChild(b);

			return block2;
		}

		private Element CompareNum(string width, int pos, string OP, long num)
		{
			var block3 = Document.CreateElement("block");
			block3.SetAttribute("type", LogicCompareBlock.type_name);

			var field = Document.CreateElement("field");
			field.SetAttribute("name", "OP");
			field.AppendChild(Document.CreateTextNode(OP));
			block3.AppendChild(field);

			var value = Document.CreateElement("value");
			value.SetAttribute("name", "A");
			block3.AppendChild(value);

			var block4 = CreateReceivedData(width, pos);
			value.AppendChild(block4);

			value = Document.CreateElement("value");
			value.SetAttribute("name", "B");
			block3.AppendChild(value);

			block4 = Document.CreateElement("block");
			block4.SetAttribute("type", MathNumberBlock.type_name);
			value.AppendChild(block4);

			field = Document.CreateElement("field");
			field.SetAttribute("name", "NUM");
			field.AppendChild(Document.CreateTextNode(num.ToString()));
			block4.AppendChild(field);

			return block3;
		}

		public void OpenModifyView(Action<bool> callback)
		{
			if (this.callback != null)
				return;
			this.callback = callback;

			Views.EObjectModalView.SetEObject(eobject, GetImageUrl());
			Views.EObjectModalView.Closed += EObjectModalView_Closed;
			Views.EObjectModalView.Render();
		}

		private void EObjectModalView_Closed(EObjectModalView view, bool ok)
		{
			view.Closed -= EObjectModalView_Closed;

			if (ok) {
				View.Identifier = eobject.identifier;
				View.ReloadToolbox(this);
				UpdateInitialBlock();
			}

			callback?.Invoke(ok);
			callback = null;
		}

		public string Template(string template)
		{
			template = template.Replace("%identifier%", eobject.identifier);
			template = template.Replace("%attribute%", "EOBJ: " + eobject.type.classGroup.classGroupCode.ToString("X2") + eobject.type.classCode.ToString("X2") + eobject.instanceCode.ToString("X2")
				+ "<br>区分: " + eobject.attribute);
			template = template.Replace("%img%", GetImageUrl());
			return template;
		}

		internal void OnBlockCreated(object sender, Create cre)
		{
			var block = workspace.getBlockById(cre.blockId);

			if (block.type == ENodeInitializeBlock.type_name) {
				var nodeBlock = (ENodeInitializeBlock)block;
				nodeBlock.OnCreate(this, cre);
			}
			else if (block.type == EObjectInitializeBlock.type_name) {
				var objectBlock = (EObjectInitializeBlock)block;
				objectBlock.OnCreate(this, cre);
			}
			else if (block.type == EPropertyVarLenBlock.type_name) {
				var propertyBlock = (EPropertyVarLenBlock)block;
				propertyBlock.OnCreate(this, cre);
			}
			else if (block.type == EPropertyFixLenBlock.type_name) {
				var propertyBlock = (EPropertyFixLenBlock)block;
				propertyBlock.OnCreate(this, cre);
			}
		}

		internal void OnBlockDeleted(object sender, Delete del)
		{
			var block = workspace.getBlockById(del.blockId);

			if (block != null) {
				if (block.type == ENodeInitializeBlock.type_name) {
					var nodeBlock = (ENodeInitializeBlock)block;
					nodeBlock.OnDelete(this, del);
				}
				else if (block.type == EObjectInitializeBlock.type_name) {
					var objectBlock = (EObjectInitializeBlock)block;
					objectBlock.OnDelete(this, del);
				}
				else if (block.type == EPropertyVarLenBlock.type_name) {
					var propertyBlock = (EPropertyVarLenBlock)block;
					propertyBlock.OnDelete(this, del);
				}
				else if (block.type == EPropertyFixLenBlock.type_name) {
					var propertyBlock = (EPropertyFixLenBlock)block;
					propertyBlock.OnDelete(this, del);
				}
			}
		}

		internal void OnBlockChanged(object sender, Change chg)
		{
			var block = workspace.getBlockById(chg.blockId);

			if (block.type == ENodeInitializeBlock.type_name) {
				var nodeBlock = (ENodeInitializeBlock)block;
				nodeBlock.OnChange(this, chg);
			}
			else if (block.type == EObjectInitializeBlock.type_name) {
				var objectBlock = (EObjectInitializeBlock)block;
				objectBlock.OnChange(this, chg);
			}
			else if (block.type == EPropertyVarLenBlock.type_name) {
				var propertyBlock = (EPropertyVarLenBlock)block;
				propertyBlock.OnChange(this, chg);
			}
			else if (block.type == EPropertyFixLenBlock.type_name) {
				var propertyBlock = (EPropertyFixLenBlock)block;
				propertyBlock.OnChange(this, chg);
			}
		}

		internal void OnBlockMoveed(object sender, Move mov)
		{
			var block = workspace.getBlockById(mov.blockId);

			if (block != null) {
				if (block.type == ENodeInitializeBlock.type_name) {
					var nodeBlock = (ENodeInitializeBlock)block;
					nodeBlock.OnMove(this, mov);
				}
				else if (block.type == EObjectInitializeBlock.type_name) {
					var objectBlock = (EObjectInitializeBlock)block;
					objectBlock.OnMove(this, mov);
				}
				else if (block.type == EPropertyVarLenBlock.type_name) {
					var propertyBlock = (EPropertyVarLenBlock)block;
					propertyBlock.OnMove(this, mov);
				}
				else if (block.type == EPropertyFixLenBlock.type_name) {
					var propertyBlock = (EPropertyFixLenBlock)block;
					propertyBlock.OnMove(this, mov);
				}
			}
		}
	}

	internal class ENodeWorkspace : EObjectWorkspace
	{
		public JsonNodeInfo enode { get { return (JsonNodeInfo)eobject; } }

		public ENodeWorkspace(BlocklyView view, JsonNodeInfo enode)
			: base(view, enode)
		{
		}

		public override string GetImageUrl()
		{
			return "img/no_image.png";
		}

		public override bool IsPreset()
		{
			return true;
		}

		public override string ToCode(string filename)
		{
			if (eobject == null)
				return "";

			_RubyCode = new Ruby(filename);
			_RubyCode.init(Workspace);
			var result = _RubyCode.defineENode((JsonNodeInfo)eobject, Workspace);
			View.Changed = false;
			return result;
		}
	}
}
