using Siger.Middlelayer.Repository.Entities;
using Siger.Middlelayer.Repository.Response;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Siger.ApiQMS.Utility
{
    public static class ChannelSectionHelper
    {
        public static string GetChannelSection(int sectionid, List<siger_project_level_section> levelSections)
        {
            string location = "";
            var section = levelSections.FirstOrDefault(t => t.id == sectionid);
            if (section != null)
            {
                location = section.title;
                var channel = levelSections.FirstOrDefault(t => t.id == section.parentid);
                if (channel != null)
                {
                    location = $"{channel.title}-{section.title}";
                }
            }
            return location;
        }

        public static IEnumerable<siger_project_level_section> GetSonLevelSections(siger_project_level_section sec, List<siger_project_level_section> sections)
        {
            var list = new List<siger_project_level_section>();
            var query = GetSonLevelSectionList(sec.id, sections);

            list.Add(sec);
            foreach (var section in query.ToList())
            {
                list.Add(section);
            }

            return list;
        }

        public static IEnumerable<siger_project_level_section> GetSonLevelSectionList(int parentId, List<siger_project_level_section> sections)
        {
            var query = from c in sections where c.parentid == parentId select c;

            return query.ToList().Concat(query.ToList().SelectMany(t => GetSonLevelSectionList(t.id, sections)));
        }

        public static List<ResponseGetSectionTree> GetSectionChildren(int parentid, int pid, int maxlevelId, List<siger_project_level_section> sections)
        {
            var response = new List<ResponseGetSectionTree>();
            var model = sections.Where(f => f.parentid.Equals(parentid));
            if (!model.Any())
            {
                return response;
            }
            foreach (var item in model)
            {
                response.Add(new ResponseGetSectionTree
                {
                    label = item.title,
                    value = item.id,
                    levelid = item.levelid == maxlevelId ? maxlevelId : 0,
                    children = GetSectionChildren(item.id, pid, maxlevelId, sections)
                });
            }
            return response;
        }
    }
}
