const [
  FeatureLayer,
  SketchViewModel,
  FeatureTemplates,
] = await $arcgis.import([
  "@arcgis/core/layers/FeatureLayer.js",
  "@arcgis/core/widgets/Sketch/SketchViewModel.js",
  "@arcgis/core/widgets/FeatureTemplates.js",
]);

const mapEl = document.querySelector("arcgis-map");
await mapEl.viewOnReady();

/*
  ステップ：編集可能なレイヤーの構築、追加
*/
const flFirePoints = new FeatureLayer({
  url: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Wildfire/FeatureServer/0",
  outFields: ["*"]
});
const flFireLines = new FeatureLayer({
  url: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Wildfire/FeatureServer/1",
  outFields: ["*"]
});
const flFirePolygons = new FeatureLayer({
  url: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Wildfire/FeatureServer/2",
  outFields: ["*"]
});

mapEl.map.addMany([flFirePoints, flFireLines, flFirePolygons]);

/*
  ステップ：FeatureTemplates の作成
*/
const featureTemplates = new FeatureTemplates({
  layers: [flFirePolygons, flFireLines, flFirePoints],
  container:"templateDiv"
});

featureTemplates.on("select", selectTemplate);

// SketchViewModel の初期化
const sketchVM = new SketchViewModel({
  layer: mapEl.view.graphics,
  view: mapEl.view,
  snappingOptions: {
    enabled: true,
  }
});
sketchVM.on("create", editFeature);

// FeatureTemplates の選択内容を入力する変数
let currentAttributes, currentFeatureLayer;

function selectTemplate(evt) {
  // 選択内容の格納
  currentAttributes = evt.template.prototype.attributes;
  currentFeatureLayer = evt.item.layer;

  // スケッチの開始
  sketchVM.create(currentFeatureLayer.geometryType, { mode: "click" });

}

function editFeature(evt) {
  // 作図の完了をハンドリング
  if (evt.state === "complete") {
    // 作図結果をグラフィックをグラフィックス レイヤーから削除
    mapEl.graphics.remove(evt.graphic);
    /*
      ステップ：作図結果とテンプレートの選択内容からグラフィックを作成
    */
    const editGraphic = evt.graphic;
    editGraphic.attributes = currentAttributes;

    /*
      ステップ：グラフィックをフィーチャ レイヤーに追加
    */
    currentFeatureLayer.applyEdits({
      addFeatures: [editGraphic]
    });

  }
}
