using ArcGIS.Core.Geometry;
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.Collections.Generic;
using System.Linq;

namespace Editing_Intro
{
  internal class EditOperationBasic : Button
  {
    protected override void OnClick()
    {
      //Get the layers I am going to work with first. 
      var pointLayer = MapView.Active.Map.GetLayersAsFlattenedList().
                First(l => l.Name == "FacilitySitePoint1");
      if(pointLayer == null) return;
      var polyLayer = MapView.Active.Map.GetLayersAsFlattenedList().
                First(l => l.Name == "FacilitySite1");
      if(polyLayer == null) return;

      QueuedTask.Run(() => {

        var centerPt = MapView.Active.Extent.Center;
        //Create the edit operation 
        var editOp = new EditOperation()
        {
          Name = "Basic Workflow",
          ErrorMessage = "The operation failed somewhere",
          SelectNewFeatures = true,
          SelectModifiedFeatures = true,
        };

        //Cue up a create
        var template = pointLayer.GetTemplate("FacilitySitePoint1");
        editOp.Create(template, centerPt);  //Could also just use the layer if there isn't a specific template

        //get the shape of the polygon
        var inspector = new Inspector();
        inspector.Load(polyLayer, 1);
        var polyshape = inspector["SHAPE"] as Polygon;

        var bufferShape = GeometryEngine.Instance.Buffer(polyshape, -300);
        //Update the shape of the polygon with the new buffer geometry
        editOp.Modify(polyLayer, 1, bufferShape);
        
        //execute the operation
        var succeed = editOp.Execute();
        if (succeed)
        {
          // on success
        }
      });
    }
  }
}
