//*******************************************************************************
// Copyright (c) 2021 Cognex Corporation. All Rights Reserved
//*******************************************************************************

using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WebView2SampleApp
{
  /// <summary>
  /// Provides externsion methods for a simple spreadsheet display of In-Sight results in a DataGridView.
  /// </summary>
  public static class SpreadsheetGridViewExtensions
  {
    public static void DoubleBufferedGrid(this DataGridView dgv, bool setting)
    {
      Type dgvType = dgv.GetType();
      PropertyInfo pi = dgvType.GetProperty("DoubleBuffered", BindingFlags.Instance | BindingFlags.NonPublic);
      pi.SetValue(dgv, setting, null);
    }

    public static void InitGrid(this DataGridView dgv)
    {
      DoubleBufferedGrid(dgv, true);

      DataTable _dt;
      _dt = new DataTable();
      dgv.DataSource = _dt;

      _dt.Columns.Add(" "); // Empty column header above row header column

      for (int col = 0; col < 26; col++)
      {
        string header = ((char)(((int)'A') + col)).ToString();
        _dt.Columns.Add(header);
      }

      for (int row = 0; row < 400; row++)
      {
        DataRow dataRow = _dt.NewRow();
        for (int col = 1; col <= 26; col++)
        {
          dataRow[col] = "";
        }
        _dt.Rows.Add(row);
      }

      dgv.Columns[0].Width = 30;
    }

    public static void UpdateGrid(this DataGridView dgv, JToken results)
    {
      if (results == null)
        return;

      int resultId = Convert.ToInt32(results["id"]);
      JArray cells = results["cells"] as JArray;

      if (cells == null)
        return;

      dgv.Invoke((Action)delegate
      {
        for (int i = 0; i < cells.Count; i++)
        {
          JToken cell = cells[i];
          string cellLocation = Convert.ToString(cell["location"]);
          if (cellLocation.Length <= 0)
            continue;

          char firstChar = cellLocation.ElementAt<char>(0);
          int colIndex = (int)firstChar - (int)'A';
          string strRow = cellLocation.Substring(1);
          int rowIndex;
          if (!int.TryParse(strRow, out rowIndex))
            continue;

          string cellValueAsText = Convert.ToString(cell["data"]);
          if (cellValueAsText.Length <= 0)
            continue;

          dgv[colIndex + 1, rowIndex].Value = cellValueAsText;
        }
      });
    }
  }
}
