using UnityEngine;
using UnityEngine.UI;
using TMPro;
using System.Linq;

public class DrawCanvas : MonoBehaviour
{
    private const int TEXTURE_RESOLUTION = 28;

    public RawImage m_canvas;
    public TextMeshProUGUI m_text;

    private Texture2D m_texture;
    private Color[] m_default;

    private DigitNeuralNetwork m_neuralNetwork;

    void Start()
    {
        m_neuralNetwork = new();

        m_texture = new Texture2D(TEXTURE_RESOLUTION, TEXTURE_RESOLUTION);
        m_default = new Color[TEXTURE_RESOLUTION * TEXTURE_RESOLUTION];
        for (int i = 0; i < m_default.Length; i++)
        {
            m_default[i] = Color.black;
        }
        m_texture.SetPixels(m_default);
        m_texture.Apply();

        m_canvas.texture = m_texture;
    }

    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            Vector2 localPoint;
            if (RectTransformUtility.ScreenPointToLocalPointInRectangle(m_canvas.rectTransform, Input.mousePosition, null, out localPoint))
            {
                int pixelX = (int)((localPoint.x + m_canvas.rectTransform.pivot.x * m_canvas.rectTransform.rect.width) / m_canvas.rectTransform.rect.width * TEXTURE_RESOLUTION);
                int pixelY = (int)((localPoint.y + m_canvas.rectTransform.pivot.y * m_canvas.rectTransform.rect.height) / m_canvas.rectTransform.rect.height * TEXTURE_RESOLUTION);
                
                if (pixelX >= 0 && pixelX < TEXTURE_RESOLUTION && pixelY >= 0 && pixelY < TEXTURE_RESOLUTION)
                {
                    m_texture.SetPixel(pixelX, pixelY, Color.white);
                    m_texture.Apply();
                }
            }
        }

        if(Input.GetMouseButton(1))
        {
            m_texture.SetPixels(m_default);
            m_texture.Apply();
        }

        if(Input.GetKey(KeyCode.C))
        {
            float[] results = m_neuralNetwork.Compute(m_texture.GetPixels().Select(x => x.r).ToArray());

            (int, float) highestResult = (0, 0f);
            for(int i = 0; i < results.Length; i++)
            {
                if(results[i] > highestResult.Item2)
                {
                    highestResult.Item1 = i;
                    highestResult.Item2 = results[i];
                }
            }

            m_text.text = highestResult.Item1.ToString();
        }
    }
}