using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.PlatformAbstractions;
using System.Linq;

namespace FinancialChartExplorer
{
    public class Startup
    {
        public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
        {
            C1.Web.Mvc.LicenseManager.Key = License.Key;
            C1.Web.Mvc.Finance.LicenseManager.Key = License.Key;
            Environment = env;

            var builder = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json")
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

            builder.AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfiguration Configuration { get; set; }

        public IHostingEnvironment Environment { get; set; }

        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddSingleton(_ => Configuration);
            //-- Eanble Session
            services.AddCaching();
            services.AddSession();
        }

        private string GetConnectionString()
        {
            var configConnectionString = Configuration["Data:DefaultConnection:ConnectionString"];
            const char folderSeparator = '\\';
            var dataFolderPath = Environment.WebRootPath.Replace('/', folderSeparator);
            if (dataFolderPath.Last() != folderSeparator)
            {
                dataFolderPath += folderSeparator;
            }

            var attachText = "AttachDbFilename=";
            var index = configConnectionString.IndexOf(attachText);
            if (index != -1)
            {
                return configConnectionString.Insert(index + attachText.Length, dataFolderPath);
            }

            return configConnectionString;
        }

        public void Configure(IApplicationBuilder app)
        {
            app.UseStaticFiles();

            app.UseSession();

            app.UseMvc(r => {
                r.MapRoute(
                    name: "default",
                    template: "{controller}/{action}/{id?}",
                    defaults: new { controller = "Home", action = "HeikinAshi" });
            });
        }
    }
}
