using System; using System.Collections.Generic; using System.Linq; using InABox.Clients; using InABox.Core; namespace InABox.DynamicGrid { public interface IDynamicEditorHost { IEnumerable Columns { get; } /// /// Loads into all columns that start with the same prefix as ; e.g, when taking a /// lookup defined for column EntityLink.ID, will contain all EntityLink.* except EntityLink.ID. /// /// This essentially gives us the other columns we need to load from the database for lookups. /// /// /// This is dumb; we don't want it, because the presence of kinda makes it redundant. /// /// The column to use the prefix of. /// The dictionary into which the columns will be loaded, in the form "FieldName": "EntityLink.FieldName" void LoadColumns(string column, Dictionary columns); /// /// In most cases, calls . /// /// /// IFilter? DefineFilter(Type type); void LoadLookups(ILookupEditorControl editor); Document? FindDocument(string filename); Document? GetDocument(Guid id); void SaveDocument(Document document); object?[] GetItems(); BaseEditor? GetEditor(DynamicGridColumn column); } public class DefaultDynamicEditorHost : IDynamicEditorHost where T : BaseObject { public virtual T[]? Items { get; set; } public IEnumerable Columns => new DynamicGridColumns().ExtractColumns(typeof(T)); public virtual IFilter? DefineFilter(Type type) => LookupFactory.DefineFilter(Items ?? Enumerable.Empty(), type); public Document? FindDocument(string filename) { return new Client().Load(new Filter(x => x.FileName).IsEqualTo(filename)).FirstOrDefault(); } public Document? GetDocument(Guid id) { Document? doc = null; if (id != Guid.Empty) doc = new Client().Load(new Filter(x => x.ID).IsEqualTo(id)).FirstOrDefault(); return doc; } public void SaveDocument(Document document) { new Client().Save(document, ""); } public BaseEditor? GetEditor(DynamicGridColumn column) => column.Editor.CloneEditor(); public object?[] GetItems() => Items ?? Array.Empty(); public void LoadColumns(string column, Dictionary columns) { columns.Clear(); var comps = column.Split('.').ToList(); comps.RemoveAt(comps.Count - 1); var prefix = string.Format("{0}.", string.Join(".", comps)); var cols = Columns.Where(x => !x.ColumnName.Equals(column) && x.ColumnName.StartsWith(prefix)); foreach (var col in cols) columns[col.ColumnName.Replace(prefix, "")] = col.ColumnName; } public void LoadLookups(ILookupEditorControl sender) { var editor = sender.EditorDefinition as ILookupEditor; var colname = sender.ColumnName; var values = editor.Values(colname, Items); sender.LoadLookups(values); } } }