using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Infrastructure.Interception;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CodeFirstStoreFunctions;

namespace FtxDemo.Data {
    public class FtxDemoContext : DbContext {

        public FtxDemoContext() : base("FtxDemo") {
            // Add fulltext command interception
            DbInterception.Add(new FtxInterceptor());
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder) {
            modelBuilder.Conventions.Add(new FunctionsConvention<FtxDemoContext>("dbo"));
        }

        public DbSet<Story> Stories { get; set; }

        [DbFunction("FtxDemoContext", "StoriesFtxSearch")]
        public IQueryable<Story> StoriesFulltext(string query) {
            if (query == null) throw new ArgumentNullException(nameof(query));
            if (string.IsNullOrWhiteSpace(query)) throw new ArgumentException("Value cannot be empty or whitespace only string.", nameof(query));

            // Create FTX query
            var ftxQuery = FtxInterceptor.CreateQuery(query, addPrefix: false);

            return ((IObjectContextAdapter)this).ObjectContext.CreateQuery<Story>("FtxDemoContext.StoriesFtxSearch(@String)", new ObjectParameter("String", ftxQuery));
        }

    }
}
