using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LiteDB;
using squirrowse.core;
using squirrowse.db;

namespace squirrowse.web.Data
{
    public class GaleryService
    {
        private readonly LiteDatabase db;

        public GaleryService(DbContext db)
        {
            this.db = db.GetRepository;
        }

        public async Task<List<string>> tags()
        {
            var tlist = new List<string>();
            //   using var db = new LiteDatabase("db.db");
            var t = db.GetCollection<Frame>();

            foreach (var frame in t.FindAll().Where(x => x.Objects != null))
            {
                var te = frame.Objects.Select(x => x.ObjectProperty).Distinct();
                tlist.AddRange(te);
            }

            return tlist.Distinct().ToList();
        }

        public async Task<Dictionary<string, List<Frame>>> galeryEntireView()
        {
            var tags = await this.tags();
            //   using var db = new LiteDatabase("db.db");
            var t = db.GetCollection<Frame>();
            var d = new Dictionary<string, List<Frame>>();

            foreach (var tag in tags)
            {
                var t1 = t.Find(frame => frame.Objects != null);
                var t2 = t1.Where(x => x.Objects.Any(y => y.ObjectProperty == tag));
                d.Add(tag, t2.ToList());
            }

            //var temp = t.Query().Select(x => x.Objects.Where().ToArray();

            // t.Find(x => x.Objects.Any(y => y.ObjectProperty == tag)).ForEach(x => { d.Add(tag, x); });
            //d.Add(tag,temp);
            return d;
        }

        public async Task<Dictionary<string, List<Frame>>> galerViewbyTag(List<string> tags)
        {
            //      using var db = new LiteDatabase("db.db");
            var t = db.GetCollection<Frame>();
            var d = new Dictionary<string, List<Frame>>();

            foreach (var tag in tags)
            {
                var t1 = t.Find(frame => frame.Objects != null);
                var t2 = t1.Where(x => x.Objects.Any(y => y.ObjectProperty == tag));
                d.Add(tag, t2.ToList());
            }

            //var temp = t.Query().Select(x => x.Objects.Where().ToArray();

            // t.Find(x => x.Objects.Any(y => y.ObjectProperty == tag)).ForEach(x => { d.Add(tag, x); });
            //d.Add(tag,temp);
            return d;
        }
    }
}