using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using OpenCvSharp;
using UnNomalized_node.communication;
using Message;
using UnNomalized_node.message;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Threading;

namespace UnNomalized_node
{
    public partial class Form1 : Form
    {
        //private OpenCamera m_camera;

        private HKVSCamera m_hk_camera;
        private FormArrow m_form_arrow = new FormArrow();
        Thread m_freash_arrow_thread = null;
        bool m_bexit = false;
        System.Windows.Forms.Timer m_timer = new System.Windows.Forms.Timer();

        public Form1()
        {
            InitializeComponent();
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            //读取配置
            tool.json_file_operation.Instance.json_file_operation_init("./unnoralized_node_settings.json");
            //初始化通讯及数据单例
            unnormalized_communication.Instance.unnormalized_communication_init();
            //连接
            JArray connect_string = tool.json_file_operation.Instance.read_json_jarray("communication_connect");
            foreach (var connect in connect_string)
            {
                unnormalized_communication.Instance.communication_connect(connect.ToString());
            }
            unnormalized_communication.Instance.communication_run();

            string ip = tool.json_file_operation.Instance.read_json_string("camera_ip");
            string user = tool.json_file_operation.Instance.read_json_string("camera_user");
            string password = tool.json_file_operation.Instance.read_json_string("camera_password");
            int port = int.Parse(tool.json_file_operation.Instance.read_json_string("camera_port"));

            //添加LED屏
            BroadcastBoardManager.Instance.AddSquareScreen(
                int.Parse(tool.json_file_operation.Instance.read_json_string("ternimalNumber")),
                Encoding.Default.GetBytes(tool.json_file_operation.Instance.read_json_string("led_screen_ip")),
                                                                5005, ONNONLed5KSDKD.Led5kSDK.bx_5k_card_type.BX_6K3, 2, 0);
            BroadcastBoardManager.Instance.squareBoardList[0].UpdateStatus(BroadcastSquareBoard.Entrance_statu.ENTRANCE_NOSIGNAL, false);
            m_hk_camera = new HKVSCamera(pictureBox_camera);
            if (m_hk_camera.init())
            {
                if(m_hk_camera.open(ip, user, password, (Int16)port))
                    m_hk_camera.view();
            }

            m_form_arrow.TopLevel = false;
            m_form_arrow.Show();
            m_form_arrow.Dock = DockStyle.Fill;
            tableLayoutPanel1.Controls.Add(m_form_arrow, 1, 1);

            this.Width = 1280;
            this.Height = 720;

            m_bexit = false;
            m_freash_arrow_thread = new Thread(fresh_image);
            m_freash_arrow_thread.Start();

            m_timer.Tick += new EventHandler(HandleTime);
            //使timer可用
            m_timer.Enabled = true;
            //设置时间间隔，以毫秒为单位
            m_timer.Interval = 100;//1s
            m_timer.Start();


            //this.Size = new System.Drawing.Size(1920, 1080);
            //若当前只有一块显示器
            var screens = Screen.AllScreens;
            if (Screen.AllScreens.Length < 2)
                return;
            //0主显示器（系统默认，可设置哪块显示器为主显示器）1扩展显示器
            this.Location = new System.Drawing.Point(screens[1].Bounds.Left, screens[1].Bounds.Top);
            this.FormBorderStyle = FormBorderStyle.None;     //设置窗体为无边框样式
            this.WindowState = FormWindowState.Maximized;    //最大化窗体

        }
        public void fresh_image()
        {
            return;
            /*while (m_bexit == false)
            {
                Bitmap image= m_hk_camera.Camera.get_bitmap();
                if (image != null)
                {
                    this.Invoke(new Action(() =>
                   {

                       if (pictureBox_camera.Image != null)
                           pictureBox_camera.Image.Dispose();
                       pictureBox_camera.Image = image;

                   }));
                   // image.Dispose();
                }
                Thread.Sleep(100);
            }*/
        }
        public void HandleTime(object sender, EventArgs e)
        {

            //m_hk_camera.Camera.draw_image_to_wnd(pictureBox_camera.Handle);
            //跟新led
           update_led_screen();

            //更新投影仪提示箭头
            TimedData<Message.Ground_status_msg> lidar_statu = communication_data.Instance.lidar_statu;
            m_form_arrow.Update_arrow();

            //跟新投影仪界面车辆信息
            string car_number_str = "";
            if (communication_data.Instance.car_license.IsTimeout() == false)
            {
                car_number_str = communication_data.Instance.car_license.Value;
            }
            car_number.Text = car_number_str+"\n"+"欢迎光临";

            //显示车辆信息
            string car_info_str = "  ";

            Message.Locate_information locate_info = lidar_statu.Value.LocateInformationRealtime;
            //
            if (lidar_statu.IsTimeout() == false)
            {

                if (lidar_statu.Value.GroundStatus == Ground_statu.CarCorrect
                   || lidar_statu.Value.GroundStatus == Ground_statu.CarBorderReached)
                {

                    if (locate_info != null)
                    {

                        car_info_str += string.Format("X:{0:.000}m Y:{1:.000}m 角度:{2:.00}°" +
                            "轴距:{3:.000}m 车宽:{4:.000}m 前轮角:{5:.00}°", locate_info.LocateX,
                            locate_info.LocateY,locate_info.LocateAngle,
                            locate_info.LocateWheelBase,locate_info.LocateWheelWidth,
                            locate_info.LocateFrontTheta);
                       
                    }
                }

            }
            label_car_info.Text = car_info_str;
        }
        private void update_led_screen()
        {
            //刷新led屏
            if (communication_data.Instance.parkspace_statu.IsTimeout())
            {
                BroadcastBoardManager.Instance.squareBoardList[0].UpdateStatus(
                    BroadcastSquareBoard.Entrance_statu.ENTRANCE_NOSIGNAL, false);
            }
            else
            {

                //根据单片机更新入口状态
                terminal_status_msg terminal_statu = communication_data.Instance.terminal_statu.Value;
                if (terminal_statu.IdStruct != null)
                {
                    if (terminal_statu.IdStruct.TerminalId == communication_data.Instance.TerminalID)
                    {
                        if (terminal_statu.SinglechipData.InsideExistenceFlag == 1)
                        {
                            BroadcastBoardManager.Instance.squareBoardList[0].UpdateStatus(
                                    BroadcastSquareBoard.Entrance_statu.ENTRANCE_OCCUPIED, false);

                        }
                        else
                        {
                            BroadcastBoardManager.Instance.squareBoardList[0].UpdateStatus(
                                    BroadcastSquareBoard.Entrance_statu.ENTRANCE_LEISURE, false);
                        }
                    }
                }
                else
                {
                    //单片机无数据显示无连接
                    BroadcastBoardManager.Instance.squareBoardList[0].UpdateStatus(
                                    BroadcastSquareBoard.Entrance_statu.ENTRANCE_NOSIGNAL, false);
                }
            }
            Message.Parkspace_allocation_status_msg parkspace_msg = communication_data.Instance.parkspace_statu.Value;

                if (parkspace_msg.LargeParkspaceRemainingNumber != 0)
                {
                    BroadcastBoardManager.Instance.squareBoardList[0].set_disp_str(" 限高:2.00");
                }
                else if (parkspace_msg.MediumParkspaceRemainingNumber != 0)
                {
                    BroadcastBoardManager.Instance.squareBoardList[0].set_disp_str(" 限高:1.70");
                }
                else if (parkspace_msg.SmallParkspaceRemainingNumber != 0)
                {
                    BroadcastBoardManager.Instance.squareBoardList[0].set_disp_str(" 限高:1.50");
                }
                else
                {
                    BroadcastBoardManager.Instance.squareBoardList[0].UpdateStatus(
                    BroadcastSquareBoard.Entrance_statu.ENTRANCE_FULL, false);
                    BroadcastBoardManager.Instance.squareBoardList[0].set_disp_str(" 车位已满");
                }

               
        }
        private void tableLayoutPanel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void pictureBox_camera_Click(object sender, EventArgs e)
        {

        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            BroadcastBoardManager.Instance.squareBoardList[0].UpdateStatus(
                                BroadcastSquareBoard.Entrance_statu.ENTRANCE_NOSIGNAL, false);
            m_bexit = true;
            m_timer.Stop();
            BroadcastBoardManager.Instance.Close();
            if (m_freash_arrow_thread.IsAlive)
            {
                m_freash_arrow_thread.Abort();
            }
            m_hk_camera.release();
            
            unnormalized_communication.Instance.communication_uninit();
            communication_data.Instance.Release();
            m_form_arrow.Close();
        }
    }
}
