﻿/*
 *  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;

namespace WebMrbc
{
	public class EcnlPropertyAttributeBlock : Block
	{
		public const string type_name = "property_attribute";

		public EcnlPropertyAttributeBlock()
			: base(type_name)
		{

		}

		public void init()
		{
			this.appendDummyInput()
				.appendField("プロパティ属性")
				.appendField(new FieldDropdown(new [] {
					new [] {"未設定", "EPC_NONE"},
					new [] {"設定可", "EPC_RULE_SET"},
					new [] {"取得可", "EPC_RULE_GET"},
					new [] {"通知有り", "EPC_RULE_ANNO"},
					new [] {"状態変化時通知", "EPC_ANNOUNCE"},
					new [] {"可変長データ", "EPC_VARIABLE"}
				}), "VALUE");
			this.setOutput(true, "Number");
			this.setColour(230);
			this.setTooltip("");
			this.setHelpUrl("http://www.example.com/");
		}
	}

	public class EcnlServiceCodeBlock : Block
	{
		public const string type_name = "service_code";

		public EcnlServiceCodeBlock()
			: base(type_name)
		{

		}

		public void init()
		{
			this.appendDummyInput()
				.appendField("サービスコード")
				.appendField(new FieldDropdown(new [] {
					new [] {"プロパティ値書き込み要求（応答不要）", "ESV_SET_I"},
					new [] {"プロパティ値書き込み要求（応答要）", "ESV_SET_C"},
					new [] {"プロパティ値読み出し要求", "ESV_GET"},
					new [] {"プロパティ値通知要求", "ESV_INF_REQ"},
					new [] {"プロパティ値書き込み・読み出し要求", "ESV_SET_GET"},
					new [] {"プロパティ値書き込み応答", "ESV_SET_RES"},
					new [] {"プロパティ値読み出し応答", "ESV_GET_RES"},
					new [] {"プロパティ値通知", "ESV_INF"},
					new [] {"プロパティ値通知（応答要）", "ESV_INFC"},
					new [] {"プロパティ値通知応答", "ESV_INFC_RES"},
					new [] {"プロパティ値書き込み・読み出し応答", "ESV_SET_GET_RES"},
					new [] {"プロパティ値書き込み要求不可応答", "ESV_SET_I_SNA"},
					new [] {"プロパティ値書き込み要求不可応答", "ESV_SET_C_SNA"},
					new [] {"プロパティ値読み出し不可応答", "ESV_GET_SNA"},
					new [] {"プロパティ値通知不可応答", "ESV_INF_SNA"},
					new [] {"プロパティ値書き込み・読み出し不可応答", "ESV_SET_GET_SNA"}
				}), "VALUE");
			this.setOutput(true, "Number");
			this.setColour(230);
			this.setTooltip("");
			this.setHelpUrl("http://www.example.com/");
		}
	}

	public class EcnlNodeIDBlock : Block
	{
		public const string type_name = "node_id";

		public EcnlNodeIDBlock()
			: base(type_name)
		{

		}

		public void init()
		{
			this.appendDummyInput()
				.appendField("ノードID")
				.appendField(new FieldDropdown(new [] {
					new [] {"アドレスID登録なし", "ENOD_NOT_MATCH_ID"},
					new [] {"マルチキャストアドレスID", "ENOD_MULTICAST_ID"},
					new [] {"自ノードアドレスID", "ENOD_LOCAL_ID"},
					new [] {"APIアドレスID", "ENOD_API_ID"},
					new [] {"他ノードID", "ENOD_REMOTE_ID"},
				}), "VALUE");
			this.setOutput(true, "Number");
			this.setColour(230);
			this.setTooltip("");
			this.setHelpUrl("http://www.example.com/");
		}
	}

	public class EcnlPropertyLocalBlock : Block
	{
		public EcnlPropertyLocalBlock(string type)
			: base(type)
		{
		}

		public string GetInputName()
		{
			var match = false;
			Block prev, block = this;
			for (;;) {
				prev = block;
				block = prev.getParent();
				if (block == null)
					break;

				if ((block.type == EPropertyVarLenBlock.type_name)
					|| (block.type == EPropertyFixLenBlock.type_name)) {
					match = true;
					break;
				}
			}

			if (!match)
				return "";

			for (var i = 0; i < block.inputList.Length; i++) {
				var input = block.inputList[i];
				if (input.connection == null)
					continue;

				var childBlock = input.connection.targetBlock();
				if (childBlock != null && childBlock.id == prev.id) {
					return input.name;
				}
			}

			return "";
		}
	}

	public class EcnlGetPropertyInfoBlock : EcnlPropertyLocalBlock
	{
		public const string type_name = "get_property_info";

		public EcnlGetPropertyInfoBlock()
			: base(type_name)
		{
		}

		public void init()
		{
			this.appendDummyInput()
				.appendField("プロパティ")
				.appendField(new FieldDropdown(new [] {
					new [] {"コード", "pcd"},
					new [] {"属性", "atr"},
					new [] {"サイズ", "sz"}
				}), "MEMBER");
			this.setOutput(true, "Number");
			this.setColour(230);
			this.setTooltip("");
			this.setHelpUrl("http://www.example.com/");
		}

		public void onchange(object ev)
		{
			if (!String.IsNullOrEmpty(GetInputName())) {
				setWarningText(null);
			}
			else {
				setWarningText("プロパティアクセスブロックのみで使用します");
			}
		}
	}

	public class EcnlSaveReceivedPropertyBlock : EcnlPropertyLocalBlock
	{
		public const string type_name = "save_received_property";

		public EcnlSaveReceivedPropertyBlock()
			: base(type_name)
		{
		}

		public void init()
		{
			this.appendDummyInput()
				.appendField("受信プロパティを保存")
				.appendField("", "ITEM");
			this.setPreviousStatement(true, null);
			this.setNextStatement(true, null);
			this.setColour(230);
			this.setTooltip("");
			this.setHelpUrl("http://www.example.com/");
		}

		public void onchange(object ev)
		{
			if (!String.IsNullOrEmpty(GetInputName())) {
				setWarningText(null);
			}
			else {
				setWarningText("プロパティアクセスブロックのみで使用します");
			}
		}
	}

	public class EcnlGetSavedPropertyBlock : EcnlPropertyLocalBlock
	{
		public const string type_name = "get_saved_property";

		public EcnlGetSavedPropertyBlock()
			: base(type_name)
		{
		}

		public void init()
		{
			this.appendDummyInput()
				.appendField("保存してあるプロパティ値")
				.appendField("", "ITEM");
			this.setOutput(true, "String");
			this.setColour(230);
			this.setTooltip("");
			this.setHelpUrl("http://www.example.com/");
		}

		public void onchange(object ev)
		{
			if (!String.IsNullOrEmpty(GetInputName())) {
				setWarningText(null);
			}
			else {
				setWarningText("プロパティアクセスブロックのみで使用します");
			}
		}
	}

	public class EcnlSetAnnounceRequestBlock : EcnlPropertyLocalBlock
	{
		public const string type_name = "set_announce_request";

		public EcnlSetAnnounceRequestBlock()
			: base(type_name)
		{
		}

		public void init()
		{
			this.appendValueInput("DATA")
				.setCheck("String")
				.appendField("受信データと");
			this.appendDummyInput()
				.appendField("を比較し変化がある場合は通知要求");
			this.setInputsInline(true);
			this.setPreviousStatement(true, null);
			this.setNextStatement(true, null);
			this.setColour(230);
			this.setTooltip("");
			this.setHelpUrl("http://www.example.com/");
		}

		public void onchange(object ev)
		{
			if (GetInputName() == "SET") {
				setWarningText(null);
			}
			else {
				setWarningText("プロパティ設定ブロックのみで使用します");
			}
		}
	}

	public class EcnlDataToNumberBlock : EcnlPropertyLocalBlock
	{
		public const string type_name = "data_to_number";

		public EcnlDataToNumberBlock()
			: base(type_name)
		{
		}

		public void init()
		{
			this.appendValueInput("POSITION")
				.setCheck("Number")
				.appendField("受信データの");
			this.appendDummyInput()
				.appendField("Byte目から")
				.appendField(new FieldDropdown(new[] {
					new [] { "1", "BYTE" },
					new [] { "2", "SHORT" },
					new [] { "4", "INT" }
				}), "WIDTH")
				.appendField("Byte分の数値");
			this.setInputsInline(true);
			this.setOutput(true, "Number");
			this.setColour(230);
			this.setTooltip("");
			this.setHelpUrl("http://www.example.com/");
		}

		public void onchange(object ev)
		{
			if (GetInputName() == "SET") {
				setWarningText(null);
			}
			else {
				setWarningText("プロパティ設定ブロックのみで使用します");
			}
		}
	}

	public class EcnlNumberToDataBlock : EcnlPropertyLocalBlock
	{
		public const string type_name = "number_to_data";

		public EcnlNumberToDataBlock()
			: base(type_name)
		{
		}

		public void init()
		{
			this.appendValueInput("POSITION")
				.setCheck("Number")
				.appendField("送信データの");
			this.appendDummyInput()
				.appendField("Byte目から")
				.appendField(new FieldDropdown(new[] {
					new [] { "1", "BYTE" },
					new [] { "2", "SHORT" },
					new [] { "4", "INT" }
				}), "WIDTH")
				.appendField("Byte分に");
			this.appendValueInput("VALUE")
				.setCheck("Number");
			this.appendDummyInput()
				.appendField("を書き込み");
			this.setInputsInline(true);
			this.setPreviousStatement(true, null);
			this.setNextStatement(true, null);
			this.setColour(230);
			this.setTooltip("");
			this.setHelpUrl("http://www.example.com/");
		}

		public void onchange(object ev)
		{
			if (GetInputName() == "GET") {
				setWarningText(null);
			}
			else {
				setWarningText("プロパティ取得アクセスブロックのみで使用します");
			}
		}
	}

	public class EcnlNoOpBlock : EcnlPropertyLocalBlock
	{
		public const string type_name = "no_op";

		public EcnlNoOpBlock()
			: base(type_name)
		{
		}

		public void init()
		{
			this.appendDummyInput()
				.appendField("処理無し");
			this.setPreviousStatement(true, null);
			this.setColour(230);
			this.setTooltip("");
			this.setHelpUrl("http://www.example.com/");
		}

		public void onchange(object ev)
		{
			if (!String.IsNullOrEmpty(GetInputName())) {
				setWarningText(null);
			}
			else {
				setWarningText("プロパティアクセスブロックのみで使用します");
			}
		}
	}

	public class EcnlReceivedDataBlock : EcnlPropertyLocalBlock
	{
		public const string type_name = "received_data";

		public EcnlReceivedDataBlock()
			: base(type_name)
		{
		}

		public void init()
		{
			this.appendDummyInput()
				.appendField("受信データ");
			this.setOutput(true, "String");
			this.setColour(230);
			this.setTooltip("");
			this.setHelpUrl("http://www.example.com/");
		}

		public void onchange(object ev)
		{
			if (GetInputName() == "SET") {
				setWarningText(null);
			}
			else {
				setWarningText("プロパティ設定ブロックのみで使用します");
			}
		}
	}

	public class EcnlReceivedDataSizeBlock : EcnlPropertyLocalBlock
	{
		public const string type_name = "received_data_size";

		public EcnlReceivedDataSizeBlock()
			: base(type_name)
		{
		}

		public void init()
		{
			this.appendDummyInput()
				.appendField("受信データサイズ");
			this.setOutput(true, "Number");
			this.setColour(230);
			this.setTooltip("");
			this.setHelpUrl("http://www.example.com/");
		}

		public void onchange(object ev)
		{
			if (!String.IsNullOrEmpty(GetInputName())) {
				setWarningText(null);
			}
			else {
				setWarningText("プロパティアクセスブロックのみで使用します");
			}
		}
	}

	public class DataJoinBlock : Block
	{
		public const string type_name = "data_join";
		internal int itemCount_;

		public DataJoinBlock()
			: base(type_name)
		{
		}

		public void init()
		{
			this.itemCount_ = 2;
			this.updateShape_();
			this.setOutput(true, "String");
			this.setMutator(new Mutator(new[] { DataCreateJoinItemBlock.type_name }));
			this.setColour(230);
			this.setTooltip("");
			this.setHelpUrl("http://www.example.com/");
		}

		public Element mutationToDom()
		{
			var container = Document.CreateElement("mutation");
			container.SetAttribute("items", this.itemCount_.ToString());
			return container;
		}

		public void domToMutation(Element xmlElement)
		{
			var count = xmlElement.GetAttribute("items");
			this.itemCount_ = count == null ? 0 : Script.ParseInt(count, 10);
			this.updateShape_();
		}

		public Block decompose(Workspace workspace)
		{
			var containerBlock = workspace.newBlock(DataCreateJoinContainerBlock.type_name);
			containerBlock.initSvg();
			var connection = containerBlock.getInput("STACK").connection;
			for (var i = 0; i < this.itemCount_; i++) {
				var itemBlock = workspace.newBlock(DataCreateJoinItemBlock.type_name);
				itemBlock.initSvg();
				connection.connect(itemBlock.previousConnection);
				connection = itemBlock.nextConnection;
			}
			return containerBlock;
		}

		public void compose(Block containerBlock)
		{
			var itemBlock = (DataCreateJoinItemBlock)containerBlock.getInputTargetBlock("STACK");
			var connections = new Connection[0];
			while (itemBlock != null) {
				connections.Push(itemBlock.valueConnection_);
				itemBlock = (itemBlock.nextConnection != null) ?
					(DataCreateJoinItemBlock)itemBlock.nextConnection.targetBlock() : null;
			}
			for (var i = 0; i < this.itemCount_; i++) {
				var connection = this.getInput("ADD" + i).connection.targetConnection;
				if (connection != null && Array.IndexOf(connections, connection) == -1) {
					connection.disconnect();
				}
			}
			this.itemCount_ = connections.Length;
			this.updateShape_();
			for (var i = 0; i < this.itemCount_; i++) {
				Mutator.reconnect(connections[i], this, "ADD" + i);
			}
		}

		public void saveConnections(Block containerBlock)
		{
			var itemBlock = (DataCreateJoinItemBlock)containerBlock.getInputTargetBlock("STACK");
			var i = 0;
			while (itemBlock != null) {
				var input = this.getInput("ADD" + i);
				itemBlock.valueConnection_ = (input != null) ?
					input.connection.targetConnection : null;
				i++;
				itemBlock = (itemBlock.nextConnection != null) ?
					(DataCreateJoinItemBlock)itemBlock.nextConnection.targetBlock() : null;
			}
		}

		private void updateShape_()
		{
			if (this.itemCount_ != 0 && this.getInput("EMPTY") != null) {
				this.removeInput("EMPTY");
			}
			else if (this.itemCount_ == 0 && this.getInput("EMPTY") == null) {
				this.appendDummyInput("EMPTY")
					.appendField("空のデータを作ります");
			}
			int i;
			for (i = 0; i < this.itemCount_; i++) {
				if (this.getInput("ADD" + i) == null) {
					var input = this.appendValueInput("ADD" + i);
					if (i == 0) {
						input.appendField("データを作ります");
					}
				}
			}
			while (this.getInput("ADD" + i) != null) {
				this.removeInput("ADD" + i);
				i++;
			}
		}
	}

	public class DataCreateJoinContainerBlock : Block
	{
		public const string type_name = "data_create_join_container";

		public DataCreateJoinContainerBlock()
			: base(type_name)
		{
		}

		public void init()
		{
			this.appendDummyInput()
				.appendField("結合");
			this.appendStatementInput("STACK");
			this.setColour(230);
			this.setTooltip("");
			this.contextMenu = false;
		}
	}

	[IgnoreCast]
	public class DataCreateJoinItemBlock : Block
	{
		public const string type_name = "data_create_join_item";
		public Connection valueConnection_;

		public DataCreateJoinItemBlock()
			: base(type_name)
		{
		}

		public void init()
		{
			this.appendDummyInput()
				.appendField("項目");
			this.setPreviousStatement(true);
			this.setNextStatement(true);
			this.setColour(230);
			this.setTooltip("");
			this.contextMenu = false;
		}
	}


	public class CreateEsvGetBlock : Block
	{
		public const string type_name = "create_esv_get";

		public CreateEsvGetBlock()
			: base(type_name)
		{
		}

		public void init()
		{
			this.jsonInit(new {
				message0 = "%1 電文の作成 %2 プロパティコード %3",
				args0 = new object[] {
					new {
						type = "field_dropdown",
						name = "TYPE",
						options = new [] {
							new [] { "読み出し要求", "esv_get" },
							new [] { "通知要求", "esv_inf_req" }
						}
					},
					new {
						type = "input_dummy"
					},
					new {
						type = "input_value",
						name = "EPC",
						check = "Number",
						align = "RIGHT"
					}
				},
				output = "EData",
				colour = 230,
				tooltip = "",
				helpUrl = "http://www.example.com/"
			});
		}
	}

	public class CreateEsvSetBlock : Block
	{
		public const string type_name = "create_esv_set";

		public CreateEsvSetBlock()
			: base(type_name)
		{
		}

		public void init()
		{
			this.jsonInit(new {
				message0 = "%1 電文の作成 %2 プロパティコード %3 プロパティ値 %4",
				args0 = new object[] {
					new {
						type = "field_dropdown",
						name = "TYPE",
						options = new [] {
							new [] { "書き込み要求（応答不要）", "esv_set_i" },
							new [] { "書き込み要求（応答要）", "esv_set_c" },
							new [] { "書き込み・読み出し要求", "esv_set_get" },
							new [] { "通知（応答要）", "esv_infc" }
						}
					},
					new {
						type = "input_dummy"
					},
					new {
						type = "input_value",
						name = "EPC",
						check = "Number",
						align = "RIGHT"
					},
					new {
						type = "input_value",
						name = "EDT",
						check = "String",
						align = "RIGHT"
					}
				},
				output = "EData",
				colour = 230,
				tooltip = "",
				helpUrl = "http://www.example.com/"
			});
		}
	}

	public class EsvAddEdtBlock : Block
	{
		public const string type_name = "esv_add_edt";

		public EsvAddEdtBlock()
			: base(type_name)
		{
		}

		public void init()
		{
			this.jsonInit(new {
				message0 = "%1 に %2 %3 として %4 %5 を追加",
				args0 = new object[] {
					new {
						type = "field_variable",
						name = "ESV",
						variable = "item"
					},
					new {
						type = "input_dummy"
					},
					new {
						type = "input_value",
						name = "EPC",
						check = "Number"
					},
					new {
						type = "input_dummy"
					},
					new {
						type = "input_value",
						name = "EDT",
						check = "String"
					}
				},
				previousStatement = (Union<string, string[]>)null,
				nextStatement = (Union<string, string[]>)null,
				colour = 230,
				tooltip = "",
				helpUrl = "http://www.example.com/"
			});
		}
	}

	public class EsvAddEpcBlock : Block
	{
		public const string type_name = "esv_add_epc";

		public EsvAddEpcBlock()
			: base(type_name)
		{
		}

		public void init()
		{
			this.jsonInit(new {
				message0 = "%1 に %2 %3 を追加",
				args0 = new object[] {
					new {
						type = "field_variable",
						name = "ESV",
						variable = "item"
					},
					new {
						type = "input_dummy"
					},
					new {
						type = "input_value",
						name = "EPC",
						check = "Number"
					}
				},
				previousStatement = (Union<string, string[]>)null,
				nextStatement = (Union<string, string[]>)null,
				colour = 230,
				tooltip = "",
				helpUrl = "http://www.example.com/"
			});
		}
	}

	public class SendEsvBlock : Block
	{
		public const string type_name = "send_esv";

		public SendEsvBlock()
			: base(type_name)
		{
		}

		public void init()
		{
			this.jsonInit(new {
				message0 = "%1 を送信",
				args0 = new object[] {
					new {
						type = "field_variable",
						name = "ESV",
						variable = "item"
					}
				},
				previousStatement = (Union<string, string[]>)null,
				nextStatement = (Union<string, string[]>)null,
				colour = 230,
				tooltip = "",
				helpUrl = "http://www.example.com/"
			});
		}
	}

	public class ReleaseEsvBlock : Block
	{
		public const string type_name = "release_esv";

		public ReleaseEsvBlock()
			: base(type_name)
		{
		}

		public void init()
		{
			this.jsonInit(new {
				message0 = "%1 を破棄",
				args0 = new object[] {
					new {
						type = "field_variable",
						name = "ESV",
						variable = "item"
					}
				},
				previousStatement = (Union<string, string[]>)null,
				nextStatement = (Union<string, string[]>)null,
				colour = 230,
				tooltip = "",
				helpUrl = "http://www.example.com/"
			});
		}
	}

	public class NotifyInitialEsvBlock : Block
	{
		public const string type_name = "notify_initial_esv";

		public NotifyInitialEsvBlock()
			: base(type_name)
		{
		}

		public void init()
		{
			this.jsonInit(new {
				message0 = "インスタンスリスト通知の送信",
				previousStatement = (Union<string, string[]>)null,
				nextStatement = (Union<string, string[]>)null,
				colour = 230,
				tooltip = "",
				helpUrl = "http://www.example.com/"
			});
		}
	}

	public class EsvGetEsvBlock : Block
	{
		public const string type_name = "esv_get_esv";

		public EsvGetEsvBlock()
			: base(type_name)
		{
		}


		public void init()
		{
			this.jsonInit(new {
				message0 = "%1 のサービスコード",
				args0 = new object[] {
					new {
						type = "field_variable",
						name = "ESV",
						variable = "item"
					}
				},
				output = "Number",
				colour = 230,
				tooltip = "",
				helpUrl = "http://www.example.com/"
			});
		}
	}

	public class EsvIterateBlock : Block
	{
		public const string type_name = "esv_iterate";

		public EsvIterateBlock()
			: base(type_name)
		{
		}

		public void init()
		{
			this.jsonInit(new {
				message0 = "%1 にある要素で繰り返し %2 %3",
				args0 = new object[] {
					new {
						type = "field_variable",
						name = "ESV",
						variable = "item"
					},
					new {
						type = "input_dummy"
					},
					new {
						type = "input_statement",
						name = "DO"
					}
				},
				previousStatement = (Union<string, string[]>)null,
				nextStatement = (Union<string, string[]>)null,
				colour = 230,
				tooltip = "",
				helpUrl = "http://www.example.com/"
			});
		}
	}

	public class EsvIteratorBlock : Block
	{
		public const string type_name = "esv_iterator";

		public EsvIteratorBlock()
			: base(type_name)
		{
		}

		public void init()
		{
			this.jsonInit(new {
				message0 = "%1",
				args0 = new object[] {
					new {
						type = "field_dropdown",
						name = "ITEM",
						options = new [] {
							new [] { "プロパティコード", "epc" },
							new [] { "プロパティ値", "edt" },
							new [] { "要素の番号", "state" }
						}
					}
				},
				output = "Number",
				colour = 230,
				tooltip = "",
				helpUrl = "http://www.example.com/"
			});
		}
	}

	public class SvctaskSetTimerBlock : Block
	{
		public const string type_name = "svctask_set_timer";

		public SvctaskSetTimerBlock()
			: base(type_name)
		{
		}

		public void init()
		{
			this.jsonInit(new {
				message0 = "%1 %2 のタイマーを %3 [ms]に設定",
				args0 = new object[] {
					new {
						type = "field_variable",
						name = "SVC",
						variable = "item"
					},
					new {
						type = "input_dummy"
					},
					new {
						type = "input_value",
						name = "TIMER",
						check = "Number"
					}
				},
				colour = 230,
				tooltip = "",
				helpUrl = "http://www.example.com/"
			});
		}
	}

	public class SvctaskTimerBlock : Block
	{
		public const string type_name = "svctask_timer";

		public SvctaskTimerBlock()
			: base(type_name)
		{
		}

		public void init()
		{
			this.jsonInit(new {
				message0 = "%1 のタイマー値",
				args0 = new object[] {
					new {
						type = "field_variable",
						name = "SVC",
						variable = "item"
					}
				},
				output = "Number",
				colour = 230,
				tooltip = "",
				helpUrl = "http://www.example.com/"
			});
		}
	}

	public class SvctaskProgressBlock : Block
	{
		public const string type_name = "svctask_progress";

		public SvctaskProgressBlock()
			: base(type_name)
		{
		}

		public void init()
		{
			this.jsonInit(new {
				message0 = "%1 %2 の時間を %3 [ms]経過させる",
				args0 = new object[] {
					new {
						type = "field_variable",
						name = "SVC",
						variable = "item"
					},
					new {
						type = "input_dummy"
					},
					new {
						type = "input_value",
						name = "ELAPSE",
						check = "Number"
					}
				},
				previousStatement = (Union<string, string[]>)null,
				nextStatement = (Union<string, string[]>)null,
				colour = 230,
				tooltip = "",
				helpUrl = "http://www.example.com/"
			});
		}
	}

	public class SvctaskRecvMsgBlock : Block
	{
		public const string type_name = "svctask_recv_msg";

		public SvctaskRecvMsgBlock()
			: base(type_name)
		{
		}

		public void init()
		{
			this.jsonInit(new {
				message0 = "%1 に %2 通信端点 %3 からの %4 データ %5 を渡す",
				args0 = new object[] {
					new {
						type = "field_variable",
						name = "SVC",
						variable = "item"
					},
					new {
						type = "input_dummy"
					},
					new {
						type = "input_value",
						name = "ENDPOINT",
						check = "String"
					},
					new {
						type = "input_dummy"
					},
					new {
						type = "input_value",
						name = "DATA",
						check = "String"
					}
				},
				previousStatement = (Union<string, string[]>)null,
				nextStatement = (Union<string, string[]>)null,
				colour = 230,
				tooltip = "",
				helpUrl = "http://www.example.com/"
			});
		}
	}

	public class SvctaskCallTimeoutBlock : Block
	{
		public const string type_name = "svctask_call_timeout";

		public SvctaskCallTimeoutBlock()
			: base(type_name)
		{
		}

		public void init()
		{
			this.jsonInit(new {
				message0 = "%1 のタイムアウト処理を行う",
				args0 = new object[] {
					new {
						type = "field_variable",
						name = "SVC",
						variable = "item"
					}
				},
				previousStatement = (Union<string, string[]>)null,
				nextStatement = (Union<string, string[]>)null,
				colour = 230,
				tooltip = "",
				helpUrl = "http://www.example.com/"
			});
		}
	}

	public class SvctaskIsMatchBlock : Block
	{
		public const string type_name = "svctask_is_match";

		public SvctaskIsMatchBlock()
			: base(type_name)
		{
		}

		public void init()
		{
			this.jsonInit(new {
				message0 = "%1 で %2 ノード %3 は %4 通信端点 %5 と %6 電文 %7 に対応している",
				args0 = new object[] {
					new {
						type = "field_variable",
						name = "SVC",
						variable = "item"
					},
					new {
						type = "input_dummy"
					},
					new {
						type = "input_value",
						name = "NODE",
						check = "EObject"
					},
					new {
						type = "input_dummy"
					},
					new {
						type = "input_value",
						name = "ENDPOINT",
						check = "String"
					},
					new {
						type = "input_dummy"
					},
					new {
						type = "input_value",
						name = "EDTAT",
						check = "String"
					}
				},
				output = "Boolean",
				colour = 230,
				tooltip = "",
				helpUrl = "http://www.example.com/"
			});
		}
	}

	partial class Ruby
	{
		public node property_attribute(EcnlPropertyAttributeBlock block)
		{
			var value = block.getFieldValue("VALUE");
			var ecnl = new const_node(this, intern("ECNL"));
			return new colon2_node(this, ecnl, intern(value));
		}

		public node service_code(EcnlServiceCodeBlock block)
		{
			var value = block.getFieldValue("VALUE");
			var ecnl = new const_node(this, intern("ECNL"));
			return new colon2_node(this, ecnl, intern(value));
		}

		public node node_id(EcnlNodeIDBlock block)
		{
			var value = block.getFieldValue("VALUE");
			var ecnl = new const_node(this, intern("ECNL"));
			return new colon2_node(this, ecnl, intern(value));
		}

		public node get_property_info(EcnlGetPropertyInfoBlock block)
		{
			var member = block.getFieldValue("MEMBER");
			var prop = new lvar_node(this, local_add_f("prop"));
			return new call_node(this, prop, intern(member));
		}

		public node save_received_property(EcnlSaveReceivedPropertyBlock block)
		{
			var src = new lvar_node(this, local_add_f("src"));
			var prop = new lvar_node(this, local_add_f("prop"));
			return new call_node(this, prop, intern("set_exinf"), new node[] { src });
		}

		public node get_saved_property(EcnlGetSavedPropertyBlock block)
		{
			var prop = new lvar_node(this, local_add_f("prop"));
			return new call_node(this, prop, intern("exinf"));
		}

		public node set_announce_request(EcnlSetAnnounceRequestBlock block)
		{
			// if (prop.anno)
			//   prop.set_anno(data != src)
			// end
			var prop = new lvar_node(this, local_add_f("prop"));
			var cond = new call_node(this, prop, intern("anno"));
			var data = valueToCode(block, "DATA");
			var src = new lvar_node(this, local_add_f("src"));
			var arg = new call_node(this, data, intern("!="), src);
			var then = new call_node(this, prop, intern("set_exinf"), new node[] { arg });
			return new if_node(this, cond, then, null, false);
		}

		public node data_to_number(EcnlDataToNumberBlock block)
		{
			var value_position = valueToCode(block, "POSITION");
			var dropdown_width = block.getFieldValue("WIDTH");
			var src = new lvar_node(this, local_add_f("src"));

			switch (dropdown_width) {
			case "BYTE":
				return new call_node(this, src, intern("getbyte"), new node[] { value_position });
			case "SHORT":
				return new fcall_node(this, intern("ecnl_getshort"), new node[] { src, value_position });
			case "INT":
				return new fcall_node(this, intern("ecnl_getint"), new node[] { src, value_position });
			}

			throw new NotImplementedException();
		}

		public node number_to_data(EcnlNumberToDataBlock block)
		{
			var value_position = valueToCode(block, "POSITION");
			var dropdown_width = block.getFieldValue("WIDTH");
			var value_value = valueToCode(block, "VALUE");
			var src = new lvar_node(this, local_add_f("src"));

			switch (dropdown_width) {
			case "BYTE":
				return new call_node(this, src, intern("setbyte"), new node[] { value_position, value_value });
			case "SHORT":
				return new fcall_node(this, intern("ecnl_setshort"), new node[] { src, value_position, value_value });
			case "INT":
				return new fcall_node(this, intern("ecnl_setint"), new node[] { src, value_position, value_value });
			}

			throw new NotImplementedException();
		}

		public node no_op(EcnlNoOpBlock block)
		{
			switch (block.GetInputName()) {
			case "SET":
				return new return_node(this, new int_node(this, 0));
			case "GET":
				return new return_node(this, new str_node(this, ""));
			}
			return new return_node(this, null);
		}

		public node received_data(EcnlReceivedDataBlock block)
		{
			return new lvar_node(this, local_add_f("src"));
		}

		public node received_data_size(EcnlReceivedDataSizeBlock block)
		{
			switch (block.GetInputName()) {
			case "SET":
			case "SET_RET":
				var src = new lvar_node(this, local_add_f("src"));
				return new call_node(this, src, intern("bytesize"));
			case "GET":
				return new lvar_node(this, local_add_f("size"));
			}
			return new int_node(this, 0);
		}

		public node data_join(DataJoinBlock block)
		{
			if (block.itemCount_ == 0) {
				return new str_node(this, "");
			}
			else if (block.itemCount_ == 1) {
				var argument0 = valueToCode(block, "ADD0");
				if (argument0 == null) argument0 = new str_node(this, "");
				return new call_node(this, argument0, intern("chr"));
			}
			else if (block.itemCount_ == 2) {
				var argument0 = valueToCode(block, "ADD0");
				if (argument0 == null) argument0 = new str_node(this, "");
				argument0 = new call_node(this, argument0, intern("chr"));
				var argument1 = valueToCode(block, "ADD1");
				if (argument1 == null) argument1 = new str_node(this, "");
				argument1 = new call_node(this, argument1, intern("chr"));
				return new call_node(this, argument0, intern("+"), new node[] { argument1 });
			}
			else {
				var codes = valueToCode(block, "ADD0");
				var argument0 = codes;
				if (argument0 == null) argument0 = new str_node(this, "");
				argument0 = new call_node(this, argument0, intern("chr"));
				for (var n = 1; n < block.itemCount_; n++) {
					var argument1 = valueToCode(block, "ADD" + n);
					if (argument1 == null) argument1 = new str_node(this, "");
					argument1 = new call_node(this, argument1, intern("chr"));
					argument0 = new call_node(this, argument0, intern("+"), new node[] { argument1 });
				}
				return codes;
			}
		}

		public node create_esv_get(CreateEsvGetBlock block)
		{
			var dropdown_type = block.getFieldValue("TYPE");
			var value_epc = valueToCode(block, "EPC");
			var nil = new nil_node(this);
			// nilにはリモートノードを指定できる
			return new fcall_node(this, intern(dropdown_type), new node[] { nil, value_epc });
		}

		public node create_esv_set(CreateEsvSetBlock block)
		{
			var dropdown_type = block.getFieldValue("TYPE");
			var value_epc = valueToCode(block, "EPC");
			var value_edt = valueToCode(block, "EDT");
			var nil = new nil_node(this);
			// nilにはリモートノードを指定できる
			return new fcall_node(this, intern(dropdown_type), new node[] { nil, value_epc, value_edt });
		}

		public node esv_add_edt(EsvAddEdtBlock block)
		{
			var variable_esv = new_var_node(get_var_name(block.getFieldValue("ESV")));
			var value_epc = valueToCode(block, "EPC");
			var value_edt = valueToCode(block, "EDT");
			return new call_node(this, variable_esv, intern("add_edt"), new node[] { value_epc, value_edt });
		}

		public node esv_add_epc(EsvAddEpcBlock block)
		{
			var variable_esv = new_var_node(get_var_name(block.getFieldValue("ESV")));
			var value_epc = valueToCode(block, "EPC");
			return new call_node(this, variable_esv, intern("add_epc"), new node[] { value_epc });
		}

		public node send_esv(SendEsvBlock block)
		{
			var variable_esv = new_var_node(get_var_name(block.getFieldValue("ESV")));
			return new fcall_node(this, intern("snd_esv"), new node[] { variable_esv });
		}

		public node release_esv(ReleaseEsvBlock block)
		{
			var variable_esv = new_var_node(get_var_name(block.getFieldValue("ESV")));
			return new fcall_node(this, intern("rel_esv"), new node[] { variable_esv });
		}

		public node notify_initial_esv(NotifyInitialEsvBlock block)
		{
			return new fcall_node(this, intern("ntf_inl"));
		}

		public node esv_get_esv(EsvGetEsvBlock block)
		{
			var variable_esv = new_var_node(get_var_name(block.getFieldValue("ESV")));
			return new call_node(this, variable_esv, intern("esv"));
		}

		public node esv_iterate(EsvIterateBlock block)
		{
			var variable_esv = new_var_node(get_var_name(block.getFieldValue("ESV")));
			local_nest();
			var statements_do = statementToCode(block, "DO");
			var itr = new arg_node(this, local_add_f("itr"));
			var proc = new block_node(this, new node[] { itr }, statements_do, false);
			local_unnest();
			return new fcall_node(this, intern("ecnl_esv_iterate"), new node[] { variable_esv }, proc);
		}

		public node esv_iterator(EsvIteratorBlock block)
		{
			var dropdown_item = block.getFieldValue("ITEM");
			var itr = new lvar_node(this, local_add_f("itr"));
			return new call_node(this, itr, intern(dropdown_item));
		}

		public node svctask_set_timer(SvctaskSetTimerBlock block)
		{
			var variable_svc = new_var_node(get_var_name(block.getFieldValue("SVC")));
			var value_timer = valueToCode(block, "TIMER");
			return new call_node(this, variable_svc, intern("set_timer"), new node[] { value_timer });
		}

		public node svctask_timer(SvctaskTimerBlock block)
		{
			var variable_svc = new_var_node(get_var_name(block.getFieldValue("SVC")));
			return new call_node(this, variable_svc, intern("timer"));
		}

		public node svctask_progress(SvctaskProgressBlock block)
		{
			var variable_svc = new_var_node(get_var_name(block.getFieldValue("SVC")));
			var value_elapse = valueToCode(block, "ELAPSE");
			return new call_node(this, variable_svc, intern("progress"), new node[] { value_elapse });
		}

		public node svctask_recv_msg(SvctaskRecvMsgBlock block)
		{
			var variable_svc = new_var_node(get_var_name(block.getFieldValue("SVC")));
			var value_endpoint = valueToCode(block, "ENDPOINT");
			var value_data = valueToCode(block, "DATA");
			return new call_node(this, variable_svc, intern("recv_msg"), new node[] { value_endpoint, value_data });
		}

		public node svctask_call_timeout(SvctaskCallTimeoutBlock block)
		{
			var variable_svc = new_var_node(get_var_name(block.getFieldValue("SVC")));
			return new call_node(this, variable_svc, intern("call_timeout"));
		}

		public node svctask_is_match(SvctaskIsMatchBlock block)
		{
			var value_node = valueToCode(block, "NODE");
			var value_edtat = valueToCode(block, "EDTAT");
			var value_endpoint = valueToCode(block, "ENDPOINT");
			return new fcall_node(this, intern("is_match"), new node[] { value_node, value_edtat, value_endpoint });
		}
	}
}
