using ArcGIS.Core.CIM;
using ArcGIS.Core.Data;
using ArcGIS.Core.Geometry;
using ArcGIS.Desktop.Catalog;
using ArcGIS.Desktop.Core;
using ArcGIS.Desktop.Editing;
using ArcGIS.Desktop.Editing.Attributes;
using ArcGIS.Desktop.Extensions;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;
using ArcGIS.Desktop.Framework.Dialogs;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Layouts;
using ArcGIS.Desktop.Mapping;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Editing_Intro
{
  internal class EditOperationOrdering_Sequential : Button
  {
    protected override void OnClick()
    {
      var fac_poly_lyr = MapView.Active.Map.GetLayersAsFlattenedList()
                      .OfType<FeatureLayer>().First(fl => fl.Name == "FacilitySite1");
      var fac_line_lyr = MapView.Active.Map.GetLayersAsFlattenedList()
                      .OfType<FeatureLayer>().First(fl => fl.Name == "FacilitySiteLine");
      if (fac_poly_lyr == null)
        return;
      if (fac_line_lyr == null)
        return;

      QueuedTask.Run(() =>
      {
        //Init
        //Get the Object ids of the features "in question"...
        var line_oid = Module1.Current.GetObjectIDs(fac_line_lyr).First();
        var poly_oid = Module1.Current.GetObjectIDs(fac_poly_lyr).First();

        //Get the geometry of the line to use in the edit operation
        var insp = new Inspector();
        insp.Load(fac_line_lyr, line_oid);
        var split_geom = insp["SHAPE"] as Polyline;

        //Set the new attribute value
        var attrib = new Dictionary<string, object>();
        attrib["LABEL_FIELD"] = "Bar";

        var editOp = new EditOperation();
        editOp.SelectModifiedFeatures = true;
        editOp.SelectNewFeatures = true;

        editOp.ExecuteMode = ExecuteModeType.Sequential;

        editOp.Name = $"{editOp.ExecuteMode.ToString()} example";

        //Do the operation.
        editOp.Split(fac_poly_lyr, poly_oid, split_geom);
        editOp.Modify(fac_poly_lyr, poly_oid, attrib);

        editOp.Execute();
      });

    }
  }
}
