﻿namespace OpenSG.Selectors
{
    
    using System.Collections.Generic;
    using System.Linq;
    using OpenQA.Selenium;
    using OpenQA.Selenium.Remote;

    class ElementSelectionPath : IElementSelector
    {
        private readonly List<IElementSelector> selectors;

        public ElementSelectionPath(List<IElementSelector> selectors)
        {
            this.selectors = selectors;
        }

        public IWebElement Resolve(RemoteWebDriver driver)
        {
            var array = selectors.ToList();

            return Select(array.First().Resolve(driver), array.Skip(1).ToList());
        }

        public IWebElement ResolveFrom(IWebElement element)
        {
            return Select(element, selectors);
        }

        private IWebElement Select(IWebElement element, List<IElementSelector> selectors)
        {
            if (selectors.Count == 0)
            {
                return element;
            }

            var first = selectors.First();

            return Select(first.ResolveFrom(element), selectors.Skip(1).ToList());
        }
    }
}
