using QC.QsprTestObjects.Tests.Base;
using QC.QsprTestObjects.Tests.DotNet;
using QC.QsprTestObjects.Tests.TestCase;

namespace QC.QTMApplication.Utilities;

public class TestPlanToTreeConverter
{
	public RootTest Convert(RootTest source)
	{
		RootTest rootTest = new RootTest(source.RealName);
		rootTest.RootProperties = new RootTestProperties(source.RootProperties);
		rootTest.RootProperties.TreeType = TreeTypes.GoNoGo;
		foreach (BaseTest test in source.TestList)
		{
			if (test is FolderTest)
			{
				rootTest.TestList.Add(ConvertFolder(test as FolderTest));
			}
			else
			{
				rootTest.TestList.Add(test);
			}
		}
		return rootTest;
	}

	private FolderTest ConvertFolder(FolderTest parent)
	{
		FolderTest folderTest = new FolderTest(parent.Properties.TestName);
		folderTest.Properties = new FolderTestProperties(parent.Properties as FolderTestProperties);
		folderTest.FolderProperties = new FolderTestProperties(parent.FolderProperties);
		folderTest.Properties.TestName = parent.Properties.TestName;
		folderTest.Properties.CheckStateTest = parent.Properties.CheckStateTest;
		foreach (BaseTest test in parent.TestList)
		{
			if (IsSingleStepTestCase(test))
			{
				folderTest.TestList.Add(ConvertSingleStepTestCase(test as TestCaseTest));
				continue;
			}
			if (test is FolderTest)
			{
				folderTest.TestList.Add(ConvertFolder(test as FolderTest));
				continue;
			}
			if (test is DotNetTest)
			{
				((DotNetTest)test).IsTestStep = false;
			}
			folderTest.TestList.Add(test);
		}
		return folderTest;
	}

	private BaseTest ConvertSingleStepTestCase(TestCaseTest parent)
	{
		if (parent.TestList.Count == 0)
		{
			return null;
		}
		BaseTest baseTest = parent.TestList[0];
		baseTest.IsTestStep = false;
		baseTest.Properties = new DotNetTestProperties(parent.FolderProperties, baseTest.Properties);
		baseTest.Properties.TestName = parent.Properties.TestName;
		baseTest.Properties.CheckStateTest = parent.Properties.CheckStateTest;
		return baseTest;
	}

	private bool IsSingleStepTestCase(BaseTest test)
	{
		if (test is TestCaseTest && ((TestCaseTest)test).TestList.Count == 1)
		{
			return true;
		}
		return false;
	}
}
