using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Owin;

namespace OwinSample
{
    class HelloWorldOwinMiddleware : OwinMiddleware
    {
        private String defaultName;
        public HelloWorldOwinMiddleware(OwinMiddleware next, string defaultName) : base(next) 
        {
            this.defaultName = defaultName;
        }
        public override async Task Invoke(IOwinContext context)
        {
            var request = context.Request;
            var response = context.Response;

            if (request.Path.ToString() != "/hello")
            {
                
                await base.Next.Invoke(context);
                return;
            }
            
            var name = defaultName;

            var nameParam = request.Query["name"];

            if (!string.IsNullOrEmpty(nameParam))
            {
                name = nameParam;
            }


            using (var bodyWriter = new StreamWriter(response.Body))
            {
                await bodyWriter.WriteAsync("<b>Hello " + name + "!</b>");
            }

        }
    }
}
