using System;
using System.Collections.Generic;
using System.IO;
using System.Management;
using System.Runtime.InteropServices;
using NUnit.Framework;

namespace TIASshot.Tests {
    /// <summary>
    /// 光源（LightSource）から切り出した判断ロジックのテスト（層①）．
    ///
    /// 仕様: SPEC_01「光源制御」
    ///   - 対応デバイス（config.xml の LightSource/Device）の表示名を含む COM ポートを使う．見つからなければ使わない
    ///   - ポートが見つからない・開けない・命令を送れないのは環境に由来する失敗として扱い，起動は止めない
    ///     （null 参照等のプログラミングエラーは握りつぶさない）
    ///   - 送れなかったときの文言は「照明の点灯（消灯）に失敗しました．光源の接続を確認してください（理由）」
    /// SelectPortName の契約: 表示名に deviceName を（大文字小文字を区別して）含む項目のうち最後の一致．
    /// 表示名が null・ポート名が空の項目は飛ばす．一覧が null か deviceName が空なら ""．
    /// シリアル通信そのもの・Form1 のボタン操作は実機（SerialPort）に依存するため層④（実機テスト light）．
    /// </summary>
    [TestFixture]
    public class LightSourceDecisionTests {

        private const string Device = "Silicon Labs CP210x";

        // ---- SelectPortName ----

        [Test]
        public void SelectPortName_一致が1件_そのポート名() {
            var ports = new List<(string Caption, string DeviceId)> {
                ("通信ポート (COM1)", "COM1"),
                ("Silicon Labs CP210x USB to UART Bridge (COM3)", "COM3"),
            };
            Assert.That(LightSource.SelectPortName(ports, Device), Is.EqualTo("COM3"));
        }

        [Test]
        public void SelectPortName_一致が複数_最後の一致() {
            var ports = new List<(string Caption, string DeviceId)> {
                ("Silicon Labs CP210x USB to UART Bridge (COM3)", "COM3"),
                ("通信ポート (COM1)", "COM1"),
                ("Silicon Labs CP210x USB to UART Bridge (COM7)", "COM7"),
            };
            Assert.That(LightSource.SelectPortName(ports, Device), Is.EqualTo("COM7"));
        }

        [Test]
        public void SelectPortName_一致なし_空文字() {
            var ports = new List<(string Caption, string DeviceId)> {
                ("通信ポート (COM1)", "COM1"),
            };
            Assert.That(LightSource.SelectPortName(ports, Device), Is.EqualTo(""));
        }

        [Test]
        public void SelectPortName_deviceNameが空_空文字() {
            var ports = new List<(string Caption, string DeviceId)> {
                ("通信ポート (COM1)", "COM1"),
            };
            Assert.That(LightSource.SelectPortName(ports, ""), Is.EqualTo(""));
        }

        [Test]
        public void SelectPortName_deviceNameがnull_空文字() {
            var ports = new List<(string Caption, string DeviceId)> {
                ("通信ポート (COM1)", "COM1"),
            };
            Assert.That(LightSource.SelectPortName(ports, null), Is.EqualTo(""));
        }

        [Test]
        public void SelectPortName_一覧がnull_空文字() {
            Assert.That(LightSource.SelectPortName(null, Device), Is.EqualTo(""));
        }

        [Test]
        public void SelectPortName_一覧が空_空文字() {
            Assert.That(LightSource.SelectPortName(new List<(string Caption, string DeviceId)>(), Device), Is.EqualTo(""));
        }

        [Test]
        public void SelectPortName_表示名がnullの項目_飛ばして他の一致を選ぶ() {
            var ports = new List<(string Caption, string DeviceId)> {
                ("Silicon Labs CP210x USB to UART Bridge (COM3)", "COM3"),
                (null, "COM9"),
            };
            Assert.That(LightSource.SelectPortName(ports, Device), Is.EqualTo("COM3"));
        }

        [Test]
        public void SelectPortName_表示名がnullの項目だけ_空文字() {
            var ports = new List<(string Caption, string DeviceId)> { (null, "COM9") };
            Assert.That(LightSource.SelectPortName(ports, Device), Is.EqualTo(""));
        }

        [Test]
        public void SelectPortName_ポート名が空の一致_飛ばして前の一致を残す() {
            var ports = new List<(string Caption, string DeviceId)> {
                ("Silicon Labs CP210x USB to UART Bridge (COM3)", "COM3"),
                ("Silicon Labs CP210x USB to UART Bridge", ""),
            };
            Assert.That(LightSource.SelectPortName(ports, Device), Is.EqualTo("COM3"));
        }

        [Test]
        public void SelectPortName_ポート名がnullの一致_飛ばして前の一致を残す() {
            var ports = new List<(string Caption, string DeviceId)> {
                ("Silicon Labs CP210x USB to UART Bridge (COM3)", "COM3"),
                ("Silicon Labs CP210x USB to UART Bridge", null),
            };
            Assert.That(LightSource.SelectPortName(ports, Device), Is.EqualTo("COM3"));
        }

        [Test]
        public void SelectPortName_大文字小文字が違う_一致しない() {
            var ports = new List<(string Caption, string DeviceId)> {
                ("silicon labs cp210x USB to UART Bridge (COM3)", "COM3"),
            };
            Assert.That(LightSource.SelectPortName(ports, Device), Is.EqualTo(""));
        }

        [Test]
        public void SelectPortName_表示名とdeviceNameが完全一致_そのポート名() {
            var ports = new List<(string Caption, string DeviceId)> { (Device, "COM4") };
            Assert.That(LightSource.SelectPortName(ports, Device), Is.EqualTo("COM4"));
        }

        // ---- IsPortFailure ----

        private static IEnumerable<TestCaseData> PortFailures() {
            yield return new TestCaseData(new UnauthorizedAccessException()).SetName("IsPortFailure_UnauthorizedAccessException_true");
            yield return new TestCaseData(new IOException()).SetName("IsPortFailure_IOException_true");
            yield return new TestCaseData(new FileNotFoundException()).SetName("IsPortFailure_IOExceptionの派生FileNotFoundException_true");
            yield return new TestCaseData(new TimeoutException()).SetName("IsPortFailure_TimeoutException_true");
            yield return new TestCaseData(new InvalidOperationException()).SetName("IsPortFailure_InvalidOperationException_true");
            yield return new TestCaseData(new ObjectDisposedException("port")).SetName("IsPortFailure_InvalidOperationExceptionの派生ObjectDisposedException_true");
            yield return new TestCaseData(new ArgumentException()).SetName("IsPortFailure_ArgumentException_true");
            yield return new TestCaseData(new ArgumentOutOfRangeException()).SetName("IsPortFailure_ArgumentExceptionの派生ArgumentOutOfRangeException_true");
            yield return new TestCaseData(new ArgumentNullException()).SetName("IsPortFailure_ArgumentExceptionの派生ArgumentNullException_true");
            yield return new TestCaseData(new ManagementException()).SetName("IsPortFailure_ManagementException_true");
            yield return new TestCaseData(new COMException()).SetName("IsPortFailure_COMException_true");
        }

        [TestCaseSource(nameof(PortFailures))]
        public void IsPortFailure_環境に由来する失敗_true(Exception ex) {
            Assert.That(LightSource.IsPortFailure(ex), Is.True);
        }

        private static IEnumerable<TestCaseData> ProgrammingErrors() {
            yield return new TestCaseData(new NullReferenceException()).SetName("IsPortFailure_NullReferenceException_false");
            yield return new TestCaseData(new Exception()).SetName("IsPortFailure_Exception_false");
            yield return new TestCaseData(new IndexOutOfRangeException()).SetName("IsPortFailure_IndexOutOfRangeException_false");
            yield return new TestCaseData(new NotSupportedException()).SetName("IsPortFailure_NotSupportedException_false");
            yield return new TestCaseData(new OutOfMemoryException()).SetName("IsPortFailure_OutOfMemoryException_false");
        }

        [TestCaseSource(nameof(ProgrammingErrors))]
        public void IsPortFailure_プログラミングエラー_false(Exception ex) {
            Assert.That(LightSource.IsPortFailure(ex), Is.False);
        }

        [Test]
        public void IsPortFailure_null_false() {
            Assert.That(LightSource.IsPortFailure(null), Is.False);
        }

        // ---- FormatSwitchFailure ----

        [Test]
        public void FormatSwitchFailure_点灯_理由あり_仕様の文言() {
            Assert.That(LightSource.FormatSwitchFailure(true, "ポートが閉じています"),
                Is.EqualTo("照明の点灯に失敗しました．光源の接続を確認してください（ポートが閉じています）"));
        }

        [Test]
        public void FormatSwitchFailure_消灯_理由あり_仕様の文言() {
            Assert.That(LightSource.FormatSwitchFailure(false, "ポートが閉じています"),
                Is.EqualTo("照明の消灯に失敗しました．光源の接続を確認してください（ポートが閉じています）"));
        }

        [Test]
        public void FormatSwitchFailure_点灯_理由がnull_括弧なし() {
            Assert.That(LightSource.FormatSwitchFailure(true, null),
                Is.EqualTo("照明の点灯に失敗しました．光源の接続を確認してください"));
        }

        [Test]
        public void FormatSwitchFailure_消灯_理由が空_括弧なし() {
            Assert.That(LightSource.FormatSwitchFailure(false, ""),
                Is.EqualTo("照明の消灯に失敗しました．光源の接続を確認してください"));
        }
    }
}
