﻿/*
 *  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.Html5;
using Bridge.jQuery2;

namespace WebMrbc
{
	internal class MainLoopWorkspace : IClassWorkspace
	{
		internal Workspace workspace;
		BlocklyView view;
		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 MainLoopWorkspace(BlocklyView view)
		{
			this.view = view;
			workspace = view.Init();

			UpdateInitialBlock();
		}

		private void UpdateInitialBlock()
		{
			var xml = Document.CreateElement("xml");
			var vset = Document.CreateElement("block");
			vset.SetAttribute("type", "variables_set");
			xml.AppendChild(vset);

			var field = Document.CreateElement("field");
			field.SetAttribute("name", "VAR");
			field.AppendChild(Document.CreateTextNode("MAKER_CODE"));
			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");
			field.AppendChild(Document.CreateTextNode("\\x00\\x00\\x00"));
			text.AppendChild(field);

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

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

		public bool IsPreset()
		{
			return true;
		}

		public string ToCode(string filename)
		{
			if (Collections.EcnlTaskWorkspace == null)
				return "";

			_RubyCode = new Ruby(filename);
			var result = _RubyCode.defineMainLoop(this, Collections.EcnlTaskWorkspace.Identifier);
			view.Changed = false;
			return result;
		}

		//Element ele;

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

		public 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);
			}
		}

		public void OpenModifyView(Action<bool> callback)
		{
			view.ReloadToolbox(this);
			callback(true);
		}

		public string Template(string template)
		{
			template = template.Replace("%identifier%", Identifier);
			template = template.Replace("%attribute%", "MainLoop");
			template = template.Replace("%img%", GetImageUrl());
			return template;
		}
	}

	partial class Ruby
	{
		internal string defineMainLoop(MainLoopWorkspace workspace, string identifier)
		{
			string code = workspaceToCode(workspace.Workspace);
			var sb = new StringBuilder();

			sb.Append(code);
			sb.AppendLine();

			sb.AppendLine($"ctrl = {identifier}.new()");
			sb.AppendLine();
			sb.AppendLine("# メインループ");
			sb.AppendLine("while (true) do");
			sb.AppendLine("	# メッセージ待ち");
			sb.AppendLine("	ret = TargetBoard::wait_msg(ctrl.timer)");
			sb.AppendLine("	if !ret then");
			sb.AppendLine("		break;");
			sb.AppendLine("	end");
			sb.AppendLine();
			sb.AppendLine("	# 経過時間の計算");
			sb.AppendLine("	ctrl.progress ret[0]");
			sb.AppendLine();
			sb.AppendLine("	# 戻り値が２つなら");
			sb.AppendLine("	if ret.length == 2 then");
			sb.AppendLine("		# 内部イベント");
			sb.AppendLine("		case (ret[1])");
			sb.AppendLine("		when 1 then");
			sb.AppendLine("			TargetBoard::restart");
			sb.AppendLine("		when 2 then");
			sb.AppendLine("			ctrl.ntf_inl");
			sb.AppendLine("		end");
			sb.AppendLine("	# 戻り値が３つなら");
			sb.AppendLine("	elsif ret.length == 3 then");
			sb.AppendLine("		# 通信レイヤーからのメッセージ（通信端点と電文）");
			sb.AppendLine("		ctrl.recv_msg(ret[1], ret[2])");
			sb.AppendLine("	end");
			sb.AppendLine();
			sb.AppendLine("	# タイムアウトの処理があれば行う");
			sb.AppendLine("	ctrl.call_timeout");
			sb.AppendLine("end");

			return sb.ToString();
		}
	}
}
