package plain;

import org.apache.catalina.Context;
import org.apache.catalina.startup.Tomcat;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import java.io.File;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.bind.annotation.*;
import java.util.List;


public class PlainMvcDemo {
    public static void main(String[] args) throws Exception {
        long t0 = System.currentTimeMillis();
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(WebConfig.class);                       // you register the config yourself

        Tomcat tomcat = new Tomcat();                        // you create the server yourself
        tomcat.setBaseDir(new File("target/tomcat").getAbsolutePath());
        tomcat.setPort(8081);
        tomcat.getConnector();
        Context web = tomcat.addContext("", new File(".").getAbsolutePath());
        Tomcat.addServlet(web, "dispatcher", new DispatcherServlet(ctx)).setLoadOnStartup(1);
        web.addServletMappingDecoded("/", "dispatcher");     // you map the DispatcherServlet yourself
        tomcat.start();
        System.out.println("PLAIN started in " + (System.currentTimeMillis() - t0) + " ms, beans: " + ctx.getBeanDefinitionCount());
        tomcat.getServer().await();
    }
}


@Configuration
@EnableWebMvc                       // turns on Spring MVC: handler mapping, message converters, ...
@ComponentScan("plain")
class WebConfig { }


@RestController
@RequestMapping("/api")
class ItemController {
    @GetMapping("/items")
    List<String> items() { return List.of("pen", "book", "lamp"); }
}
