// Copyright (c) Microsoft Corporation. 
// Licensed under the MIT license. 

using Simplygon.Unity;
using SimplygonUI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEditor;
using UnityEditor.IMGUI.Controls;
using UnityEngine;

namespace SimplygonUI
{
    public class SimplygonPipelineDropdownItem : AdvancedDropdownItem
    {
        public SimplygonPipeline Target { get; protected set; }
        public SimplygonPipelineDropdownItem(string name, SimplygonPipeline target) : base(name)
        {
            Target = target;
        }
    }

    public class SimplygonPipelineDropdown : AdvancedDropdown
    {
        ISimplygonPipelineDropdownCallback Callback;
        public SimplygonPipelineDropdown(ISimplygonPipelineDropdownCallback callback) : base(new AdvancedDropdownState())
        {
            Callback = callback;
            minimumSize = new UnityEngine.Vector2(minimumSize.x, minimumSize.y + 175);
        }

        protected override AdvancedDropdownItem BuildRoot()
        {
            var root = new AdvancedDropdownItem("LOD Component");

            foreach (var pipelineTemplate in SimplygonPipelineDatabase.PipelineTemplates)
            {
                List<string> pathList = null;
                pathList = pipelineTemplate.MenuPath.Split('/').ToList();
                if (pathList.Count > 0)
                {
                    pathList.Reverse();
                    Stack<string> path = new Stack<string>(pathList);
                    BuildDropdownItem(root, path, pipelineTemplate);
                }
            }

            return root;
        }

        protected void BuildDropdownItem(AdvancedDropdownItem parent, Stack<string> path, SimplygonPipeline target)
        {
            string childName = path.Pop();
            AdvancedDropdownItem child = parent.children.Where(i => i.name == childName).FirstOrDefault();

            if (child == null)
            {
                if(path.Count == 0)
                {
                    child = new SimplygonPipelineDropdownItem(childName, target);
                }
                else
                {
                    child = new AdvancedDropdownItem(childName);
                }
                
                parent.AddChild(child);
            }

            if (path.Count > 0)
            {
                BuildDropdownItem(child, path, target);
            }
        }

        protected override void ItemSelected(AdvancedDropdownItem item)
        {
            Callback.NewLODComponentSelected(item);
        }
    }
}
