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 PS_SDK_Net;

namespace Sample
{
    public partial class OpenSessionDlg : Form
    {
        CameraManager cameraManager;
        public int SelectedCameraId { get; private set; }

        class CameraInfoItem
        {
            public string name { get; set; }
            public int id { get; set; }

            public CameraInfoItem(string name_, int id_)
            {
                name = name_;
                id = id_;
            }
        }

        public OpenSessionDlg()
        {
            InitializeComponent();

            lbCameras.DisplayMember = "name";

            cameraManager = new CameraManager();
            cameraManager.CameraListChanged += cameraManager_CameraListChanged;

            ReloadCameraList();
            RealizeOkButton();
        }

        void cameraManager_CameraListChanged(PSCameraInfo cameraInfo, 
            PSCameraConnectionState state)
        {
            Invoke(new MethodInvoker(() => ReloadCameraList()));
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = System.Windows.Forms.DialogResult.Cancel;
            Close();
        }

        private void ReloadCameraList()
        {
            lbCameras.Items.Clear();

            foreach (var i in cameraManager.CameraList)
                lbCameras.Items.Add(new CameraInfoItem(i.name, i.id));
            
            if (lbCameras.Items.Count > 0)
                lbCameras.SelectedIndex = 0;
            
            RealizeOkButton();
        }

        private void RealizeOkButton()
        {
            btnOK.Enabled = lbCameras.SelectedIndex >= 0;
        }

        private void lbCameras_SelectedIndexChanged(object sender, EventArgs e)
        {
            RealizeOkButton();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (lbCameras.SelectedIndex < 0)
                return;
            SelectedCameraId = (lbCameras.SelectedItem as CameraInfoItem).id;
            DialogResult = System.Windows.Forms.DialogResult.OK;
            Close();
        }

        private void OpenCameraDlg_FormClosed(object sender, FormClosedEventArgs e)
        {
            cameraManager.CameraListChanged -= cameraManager_CameraListChanged;
        }
    }
}