using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using DbContextLifetimeSample.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.EntityFrameworkCore;
using System.Data.SqlClient;

namespace DbContextLifetimeSample.Controllers
{
    public class HomeController : Controller
    {
        private readonly IConfiguration _configuration = null;

        private readonly BloggingContext _context = null;

        public HomeController(IConfiguration configuration, BloggingContext context = null)
        {
            _configuration = configuration;
            _context = context;
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Test()
        {
            var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
            optionsBuilder.UseSqlServer(_configuration.GetConnectionString("blogging"));

            BloggingContext context = new BloggingContext(optionsBuilder.Options);

            //context.Database.EnsureCreated();


            //using (BloggingContext context = new BloggingContext(optionsBuilder.Options))
            //{
            //    var blog = context.Blogs.Find(1);
            //    //var posts= blog.Posts //需要访问数据库拿到导航属性的值。
            //}

            //context.Database.OpenConnection();

            //context.Database.CloseConnection();

            //SqlConnection.ClearAllPools();
            //context.Database.GetDbConnection().Close();

            //for (int i = 0; i < 20; i++)
            //{
            //    var context2 = new BloggingContext(optionsBuilder.Options);
            //    context2.Database.OpenConnection();
            //}

            //Task.Delay(TimeSpan.FromSeconds(15)).Wait();

            Task.Run(()=> {

                while (true)
                {
                    context.Add(new Blog { Url="www.xcode.me" });
                    context.SaveChanges();
                }
            });

            Task.Run(() => {

                while (true)
                {
                    context.Add(new Blog { Url = "www.xcode.me" });
                    context.SaveChanges();
                }
            });

            Task.Delay(TimeSpan.FromHours(15)).Wait();

            return Ok(Guid.NewGuid());
        }
    }
}