//*******************************************************************************
// Copyright (C) 2021 Cognex Corporation
//
// Subject to Cognex Corporation's terms and conditions and license agreement,
// you are authorized to use and modify this sample source code in any way you find
// useful, provided the Software and/or the modified Software is used solely in
// conjunction with a Cognex Machine Vision System.  Furthermore you acknowledge
// and agree that Cognex has no warranty, obligations or liability for your use
// of the Software.
//*******************************************************************************

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json.Linq;
using Microsoft.Web.WebView2.Core;
using System.Reflection;

using Cognex.InSight.WebAPI;

namespace WebView2SampleApp
{
  public partial class MainForm : Form
  {
    // Holds the sessionID that was created in the HMI page
    private string _sessionID = "";

    // A flag that is set to true after the content is fully loaded
    private bool _contentLoaded = false;

    // A Timer that is used to refresh the grid results
    private System.Windows.Forms.Timer _timer;

    // The Task that initialized the WebView2 control
    private Task _browserInitializeTask;

    public MainForm()
    {
      InitializeComponent();

      gridView.InitGrid();
      
      // Update the spreadsheet every 50ms
      _timer = new System.Windows.Forms.Timer();
      _timer.Interval = 50;
      _timer.Tick += _timer_Tick;
      _timer.Start();
    }
    
    private async void _timer_Tick(object sender, EventArgs e)
    {
      if (_contentLoaded)
      {
        JToken results = await HmiWebPageInterop.getResultsFromDisplay(webView);
        gridView.UpdateGrid(results);
      }
    }

    private void WebView_CoreWebView2InitializationCompleted(object sender, Microsoft.Web.WebView2.Core.CoreWebView2InitializationCompletedEventArgs e)
    {
      webView.NavigationCompleted += webView_NavigationCompleted;
    }

    private async void webView_NavigationCompleted(object sender, Microsoft.Web.WebView2.Core.CoreWebView2NavigationCompletedEventArgs e)
    {
      int retries = 5;
      while (retries > 0)
      {
        try
        {
          // Wait until the page is completely loaded (i.e. an HmiSession is available).
          System.Threading.Thread.Sleep(2000);
          Application.DoEvents();

          // Get the session ID that can be used to issue HmiSession messages
          object returnObj = await webView.CoreWebView2.ExecuteScriptAsync("window.ResourceManager.TagManager._subscriptionGroupId");
          _sessionID = await HmiWebPageInterop.getSessionID(webView);

          // Update the grid the the text value of the cells that are loaded from the WebView2 that displays the HMI page
          JToken results = await HmiWebPageInterop.getResultsFromDisplay(webView);
          gridView.UpdateGrid(results);

          _contentLoaded = true;
          break;
        }
        catch (Exception ex)
        {
          Debug.WriteLine($"webView_NavigationCompleted: {ex.Message}");
          retries--;
        }
      }
    }

    private void btnGo_Click(object sender, EventArgs e)
    {
      string url = "http://" + tbAddressAndPort.Text + "?page=ImageAndGraphics";
      lblUrl.Text = "Url: " + url;

      // Open the ImageAndGraphics page
      webView.Source = new Uri(url);
    }

    private void MainForm_Load(object sender, EventArgs e)
    {
      webView.CoreWebView2InitializationCompleted += WebView_CoreWebView2InitializationCompleted;
      _browserInitializeTask = webView.EnsureCoreWebView2Async();
    }

    private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
    {
      _timer.Stop();
    }
  }
}
