using System;
using Unity.Collections;
using UnityEngine;
using UnityEngine.UI;

public class WhiteBoradClient : MonoBehaviour
{
    TcpCommunication tcpCommunication = new TcpCommunication(); // NCAgp

    const int width = 360;// RawImageɐݒ肷Texture2D̃TCY
    const int height = 360;
    //const string filePath = "white_board.bin";//ĨC[WLpt@C
    public static int brushSize = 3;// LF̂̃TCY̋`uVƂĎg
    RawImage rawImage;// CanvasςɔzuRawImageŁA`Ώ

    void Start()
    {
        Time.fixedDeltaTime = 0.02f;//Application.targetFrameRate = 50;ɑŒt[Ԋuw

        TcpAppServer.onGUI_width = 300;//OnGUI()Ŏg\ύX
        TcpAppServer.onGUI_TextFieldFontSize = 24;//OnGUI()Ŏg\TCXύX
        TcpAppServer.onGUI_LabelFontSize = 14;
        TcpAppServer.onGUI_ButtonFontSize = 16;
        TcpAppServer.onGUI_flagServer = false;//onGUIT[oN\̂ݏ
        TcpCommunication.onGUI_LabelFontSize = 16;

        TcpCommunication.clientId = "Red"; // RɎgŁA͐FwɎgB
        TcpCommunication.target_IP = "192.168.0.110"; // ftHgڑIPAhXisɕύX\j
        TcpCommunication.tcp_port = 51234;// T[oŎg|[gԍisɕύX\j

        TcpCommunication.tcpClientButton += () => {// TcpAppServer̐ڑpGUI{^Ŏs
            TcpAppServer.onGUI_flagClient = false;//onGUINCAg̐ڑ\̂ݏ       
            tcpCommunication.ConnectTo();// TcpCommunication.target_IP,TcpCommunication.tcp_portɐڑ
        };

        tcpCommunication.onConnect += () => {
            TcpAppServer.onGUI_flag = true;// fobNȂȂflaseɂƗǂB
            TcpCommunication.onGUI_message += "ڑI"; // fobNp
        };

        GameObject rawImageObj = GameObject.Find("RawImage");
        this.rawImage = rawImageObj.GetComponent<RawImage>();
        Color32 color = new Color32(255, 255, 255, 255);
        this.rawImage.texture = createTexture(width, height, color);// colorFTexture2D𐶐;
    }

    void FixedUpdate()
    {
        if (Input.GetMouseButton(0))// {^
        {
            // FƁANbN̑M𐶐āAM
            Vector3 pos = Input.mousePosition;
            Vector3 viewPos = Camera.main.ScreenToViewportPoint(pos);
            int x = (int)(viewPos.x * width);
            int y = (int)(viewPos.y * height);
            Debug.Log($"viewPos={viewPos}x ={x:000}y={y:000}");
            string sendMsg = $"{TcpCommunication.clientId},{x},{y}";
            this.tcpCommunication.SendMessage(sendMsg); // T[oɑM
        }

        // NCAg̎M(MŌ̃pPbgoBr̃pPbgłꍇ)
        BinPacket binPacket = null;
        for (;;)
        {
            // M̎o
            BinPacket tempPacket = QueueBuffer.GetBuff(tcpCommunication.queueBuffer);
            if (tempPacket == null) break;
            binPacket = tempPacket;
        }
        if (binPacket == null) return; // MpPbg

        // MpPbgŁArawImage.textureXV
        byte[] bytes = BinPacket.getData(binPacket.packet);//MpPbgAẽoCioB

        Texture2D texture = (Texture2D)this.rawImage.texture;
        Color32[] pixels = texture.GetPixels32();
        BytesToColor32(bytes,pixels);
        texture.SetPixels32(pixels);// Mf[^ŉʂXV
        texture.Apply();
    }

    private void OnGUI()
    {
        TcpCommunication.OnGUI_Sub();// TcpCommunication.messgae ̕\ifobNpj
    }

    public static Texture2D createTexture(int width, int height, Color32 color)
    {
        Texture2D texture = new Texture2D(width, height, TextureFormat.RGBA32, false);
        NativeArray<Color32> pixels = texture.GetRawTextureData<Color32>();
        Debug.Log($"{pixels.Length}  ( {texture.height}, {texture.width})");
        for (int i = 0; i < pixels.Length; i++)
        {
            pixels[i] = color;
        }
        texture.Apply();
        return texture;
    }

    // bytez񂩂pixelszݒ
    public static void BytesToColor32(byte[] bytes, Color32[] pixels)
    {
        bool chk = bytes.Length == pixels.Length * 4;
        if (chk == false) throw new Exception("BytesToColor32: {bytes.Length]bytepixelsɐݒo܂B");
        for (int idx_bytes = 0, idx = 0; idx < pixels.Length; idx++)
        {
            byte r = bytes[idx_bytes++];
            byte g = bytes[idx_bytes++];
            byte b = bytes[idx_bytes++];
            byte a = bytes[idx_bytes++];
            pixels[idx] = new Color32(r, g, b, a);
        }
    }
}

