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

namespace OwinSample
{

    using AppFunc = Func<IDictionary<string, object>, Task>;

    //
    //  Anmerkung zur Preview: Funktioniert nicht in Preview
    //
    public class UglyHelloWorldOwinMiddleware /*: OwinMiddleware*/
    {
        private String defaultName;
        private AppFunc Next;
        public UglyHelloWorldOwinMiddleware(AppFunc next, String defaultName)
        {
            this.defaultName = defaultName;
            this.Next = next;
        }

        public /* override */ /* async */ Task Invoke(IDictionary<string, object> env)
        {

            var requestPath = (string)env["owin.RequestPath"];

            if (requestPath != "/hello")
            {
                return Next.Invoke(env);
            }

            var requestMethod = (string)env["owin.RequestMethod"];
            var responseBody = (Stream)env["owin.ResponseBody"];
            var responseHeaders = (IDictionary<string, string[]>)env["owin.ResponseHeaders"];

            using (var responseWriter = new StreamWriter(responseBody))
            {
                Debug.WriteLine(requestMethod + " " + requestPath);

                responseHeaders["Content-Type"] = new[] { "text/html" };

                return responseWriter.WriteLineAsync("<b>" + "Hello World!" + "</b>");

            }

        }
    }
}
