using ArcGIS.Desktop.Editing;
using ArcGIS.Desktop.Editing.Attributes;
using ArcGIS.Desktop.Framework.Contracts;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Mapping;
using System;
using System.Linq;

namespace Editing_Intro
{
  internal class UsingInspectorForCreate : Button
  {
    protected override void OnClick()
    {
      //Getting the layers
      var polyLayer = MapView.Active.Map.GetLayersAsFlattenedList().
                OfType<FeatureLayer>().First(l => l.Name == "FacilitySite1");
      if (polyLayer == null) return;
      var pointLayer = MapView.Active.Map.GetLayersAsFlattenedList().
                OfType<FeatureLayer>().First(l => l.Name == "FacilitySitePoint1");
      if (pointLayer == null) return;

      QueuedTask.Run(() => {

        var centerPt = MapView.Active.Extent.Center;

        var inspector = new Inspector();
        inspector.Load(pointLayer, 25);
        //define a shape. 
        inspector.Shape = centerPt;
        inspector["LASTUPDATE"] = DateTime.Now;
        inspector["LASTEDITOR"] = "Dev and Tech";

        //can also enumerate the dictionary to obtain attributes
        foreach (var attrib in inspector)
        {
          System.Diagnostics.Debug.WriteLine($"{attrib.FieldAlias}: {attrib.CurrentValue.ToString()}");
        }

        //Create the edit operation  
        var editOp = new EditOperation()
        {
          Name = "Create + Modify Features",
          CancelMessage = "Create + Modify Features cancelled",
          SelectNewFeatures = true, 
          SelectModifiedFeatures = true,
        };

        //Uses the attributes and the new shape defined in the inspector to create a new point feature.
        editOp.Create(inspector.MapMember, inspector);

        #region Modify

        ////The copy attributes to a different feature remove the shape field
        ////Linq ToDictionary
        //var dict_copy = inspector.ToDictionary(a => a.FieldName, a => a.CurrentValue);
        //dict_copy.Remove("SHAPE");
        //dict_copy["LASTUPDATE"] = DateTime.Now;
        //dict_copy["LASTEDITOR"] = "Dev and Tech";

        //editOp.Modify(pointLayer, 28, dict_copy);
        #endregion

        editOp.Execute();

      });
    }
  }
}


