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

namespace WebMrbc
{
	public class EObjectModalView
	{
		jQuery el;
		JsonObjectInfo model;
		JsonObjectInfo target;
		JsonClassGroupInfo currentClassGroup;

		public event Action<EObjectModalView, bool> Closed;

		public EObjectModalView()
		{
			el = jQuery.Select("#eobject-modal");
		}

		internal void SetEObject(JsonObjectInfo eobject, string imgUrl)
		{
			target = eobject;
			model = eobject.Clone();

			var cg = model.type.classGroup;
			if ((model.attribute == "device") && (model.type == App.NodeProfileClass)) {
				cg = App.ClassGroups[0];
			}

			var img = (new jQuery("<img>"));
			img.Attr("src", imgUrl);
			img.Attr("alt", model.identifier);
			jQuery.Select("#eobject-modal-eobject img").ReplaceWith(img);

			jQuery.Select("#eobject_identifier").Val(model.identifier);
			jQuery.Select("#eobject_instanceCode").Val(model.instanceCode.ToString());
			SetAttribute(model.attribute);

			SetClassGroup(cg, () => {
				var c = model.type;
				if ((model.attribute == "device") && (model.type == App.NodeProfileClass)) {
					c = App.ClassGroups[0].classes[0];
				}
				SetClass(c, UpdateProperties);
			});
		}

		internal void Render()
		{
			el.Modal(new ModalOptions() {
				Backdrop = "static",
				Show = true
			});
		}

		private void SetAttribute(string attribute)
		{
			var dropdown = jQuery.Select("#eobject_attribute").Parent();
			var button = jQuery.Select("button[type='button']", dropdown);
			button.Attr("disabled", "disabled");

			var menuitem = jQuery.Select("a[role='menuitem']", dropdown);

			string text;
			switch (attribute) {
			case "local":
				text = menuitem.Get(0).TextContent;
				break;
			case "sync":
				text = menuitem.Get(1).TextContent;
				break;
			case "async":
				text = menuitem.Get(2).TextContent;
				break;
			case "device":
				text = menuitem.Get(3).TextContent;
				break;
			default:
				text = attribute;
				break;
			}

			SetAttribute(attribute, text);
		}

		private void SetAttribute(string attribute, string text)
		{
			model.attribute = attribute;

			var button = jQuery.Select("#eobject_attribute");
			button.Text(text);

			var caret = jQuery.Select("span.caret", button);
			if (caret.Length == 0) {
				caret = new jQuery(ElementType.Span);
				caret.Attr("class", "caret");
				button.Append(caret);
			}
		}

		private void SetClassGroup(JsonClassGroupInfo cg, Action success = null)
		{
			currentClassGroup = cg;

			var button = jQuery.Select("#eobject_classGroupCode");
			button.Text(cg.description);

			if (model.attribute == "device") {
				button.RemoveAttr("disabled");
			}
			else {
				button.Attr("disabled", "disabled");
			}

			var caret = jQuery.Select("span.caret", button);
			if (caret.Length == 0) {
				caret = new jQuery(ElementType.Span);
				caret.Attr("class", "caret");
				button.Append(caret);
			}

			InitClasss(cg);
			if (success != null) success();
		}

		private void SetClass(JsonClassInfo c, Action success = null)
		{
			model.type = c;

			var button = jQuery.Select("#eobject_classCode");
			button.Text(c.description);

			if (model.attribute == "device") {
				button.RemoveAttr("disabled");
			}
			else {
				button.Attr("disabled", "disabled");
			}

			var caret = jQuery.Select("span.caret", button);
			if (caret.Length == 0) {
				caret = new jQuery(ElementType.Span);
				caret.Attr("class", "caret");
				button.Append(caret);
			}

			string identifier = jQuery.Select("#eobject_identifier").Val();
			if (model.identifier == identifier) {
				model.identifier = CodeGenerator.GetClassIdentifier(c);
				jQuery.Select("#eobject_identifier").Val(model.identifier);
			}

			InitProperties(c);
			if (success != null) success();
		}

		internal void InitClassGroups()
		{
			var ul = jQuery.Select("#eobject_classGroups");

			ul.Html("");

			foreach (var cg in App.ClassGroups) {
				var li = new jQuery(ElementType.LI);
				li.Attr("role", "presentation");

				var a = new jQuery(ElementType.Anchor);
				a.Attr("role", "menuitem");
				a.Append(cg.description);
				a.Click(cg, new Action<jQueryMouseEvent>(OnSelectClassGroupCode));

				li.Append(a);
				ul.Append(li);
			}
		}

		internal void InitClasss(JsonClassGroupInfo cg)
		{
			var ul = jQuery.Select("#eobject_classs");

			ul.Html("");

			foreach (var c in cg.classes) {
				var li = new jQuery(ElementType.LI);
				li.Attr("role", "presentation");

				var a = new jQuery(ElementType.Anchor);
				a.Attr("role", "menuitem");
				a.Append(c.description);
				a.Click(c, new Action<jQueryMouseEvent>(OnSelectClassCode));

				li.Append(a);
				ul.Append(li);
			}
		}

		internal void InitProperties(JsonClassInfo c)
		{
			var div = jQuery.Select("#eobject_properties");

			div.Html("");

			if (c.classGroup.classGroupCode != 0x0E || c.classCode != 0xF0) {
				foreach (var p in App.BaseObjectPropertyList) {
					InitProperty(div, p);
				}
			}

			foreach (var p in c.properties) {
				InitProperty(div, p);
			}
		}

		private void InitProperty(jQuery div, JsonPropertyInfo p)
		{
			var label = new jQuery(ElementType.Label);
			label.Attr("class", "btn btn-default");

			var input = new jQuery(ElementType.Input);
			input.Attr("type", "checkbox");
			input.Attr("autocomplete", "off");

			label.Append(input);
			label.Append(p.description);
			label.Attr("data-ecnl-epc", p.propertyCode.ToString());

			div.Append(label);

			if ((p.required.Length > 0) && (p.required[0] != "NONE")) {
				label.ButtonToggle();
			}
		}

		private void UpdateProperties()
		{
			var labels = jQuery.Select("#eobject_properties > .btn.btn-default");

			foreach (Element l in labels.Get()) {
				var label = new jQuery(l);
				if (label.Is(".active"))
					label.ButtonToggle();

				var sepc = label.Attr("data-ecnl-epc");
				if (sepc == null)
					continue;

				var epc = Script.ParseInt(sepc);
				JsonPropertyInfo prop = null;
				foreach (var p in model.properties) {
					if (p.propertyCode != epc)
						continue;
					prop = p;
					break;
				}
				if (prop != null) {
					label.ButtonToggle();
				}
			}
		}

		[Convention(Notation.CamelCase)]
		public void OnChangeIdentifier(Element ele)
		{
			var identifier = jQuery.Select("#eobject_identifier").Val();
			model.identifier = identifier;
		}

		[Convention(Notation.CamelCase)]
		public void OnSelectAttribute(Element sender, string attribute)
		{
			var text = sender.TextContent;
			SetAttribute(attribute, text);
		}

		[Convention(Notation.CamelCase)]
		public void OnSelectClassGroupCode(jQueryMouseEvent e)
		{
			var cg = (JsonClassGroupInfo)e.Data;
			SetClassGroup(cg, () => {
				SetClass(cg.classes[0], UpdateProperties);
			});
		}

		[Convention(Notation.CamelCase)]
		public void OnSelectClassCode(jQueryMouseEvent e)
		{
			SetClass((JsonClassInfo)e.Data, UpdateProperties);
		}

		[Convention(Notation.CamelCase)]
		public void OnChangeInstanceCode(Element sender)
		{
			model.instanceCode = (byte)Script.ParseInt((new jQuery(sender)).Val());
		}

		[Convention(Notation.CamelCase)]
		public void OnOk(Element ele)
		{
			if ((model.attribute == "device") && (model.type == App.NodeProfileClass)) {
				return;
			}

			el.Modal(ModalOperation.Hide);

			target.type = model.type;
			target.identifier = model.identifier;
			target.parent = model.parent;
			target.instanceCode = model.instanceCode;
			target.attribute = model.attribute;
			target.properties = new JsonPropertyInfo[0];

			var labels = jQuery.Select("#eobject_properties > .btn.btn-default");

			foreach (Element l in labels.Get()) {
				var label = new jQuery(l);
				if (!label.Is(".active"))
					continue;

				var sepc = label.Attr("data-ecnl-epc");
				if (sepc == null)
					continue;

				var epc = Script.ParseInt(sepc);
				JsonPropertyInfo prop = null;
				if (model.type.classGroup.classGroupCode != 0x0E || model.type.classCode != 0xF0) {
					foreach (var p in App.BaseObjectPropertyList) {
						if (p.propertyCode != epc)
							continue;
						prop = p;
						break;
					}
				}
				if (prop != null) {
					target.properties.Push(prop);
				}
				else {
					foreach (var p in model.type.properties) {
						if (p.propertyCode != epc)
							continue;
						prop = p;
						break;
					}
					if (prop != null) {
						target.properties.Push(prop);
					}
				}
			}

			if (Closed != null)
				Closed(this, true);
		}

		[Convention(Notation.CamelCase)]
		public void OnCancel(Element ele)
		{
			el.Modal(ModalOperation.Hide);

			if (Closed != null)
				Closed(this, false);
		}
	}
}
