package net.tccn.base;

import net.tccn.user.MUser;
import net.tccn.user.UserService;
import org.redkale.net.http.HttpRequest;
import org.redkale.net.http.HttpResponse;
import org.redkale.net.http.HttpServlet;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.logging.Logger;

/**
 * @author: liangxianyou at 2018/11/8 17:05.
 */
public class BaseServlet extends HttpServlet {

    @Resource(name = "SERVER_ROOT")
    protected File webroot;
    @Resource
    private UserService userService;

    public Logger logger = Logger.getLogger(this.getClass().getSimpleName());
    public static final boolean winos = System.getProperty("os.name").contains("Window");

    @Override
    protected void preExecute(HttpRequest request, HttpResponse response) throws IOException {
        String sessionid = request.getParameter("token");
        if (sessionid == null) {
            sessionid = request.getHeader("token");
        }
        if (sessionid == null) {
            sessionid = request.getSessionid(true);
        }
        if (sessionid == null) {
            Map<String, String> headers = request.getHeaders();
            for (String key : headers.keySet()) {
                if ("token".equalsIgnoreCase(key)) {
                    sessionid = headers.get(key);
                    break;
                }
            }
        }

        if (sessionid != null) {
            MUser user = userService.current(sessionid);
            /*request.setCurrentUserSupplier(() -> {
                return user;
            });*/
            if (user != null) {
                request.setCurrentUserid(user.getUserid());
            }
        }
        String uri = request.getRequestURI();
        if (uri.endsWith(".html")) {
            response.finish(new File(webroot + uri));
            return;
        }

        super.preExecute(request, response);
    }

    @Override
    protected void authenticate(HttpRequest request, HttpResponse response) throws IOException {
        //fixme: 权限拦截
        if (request.currentUserid(String.class) == null) {
            String accept = request.getHeader("Accept");
            if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With")) || (accept != null && accept.contains("application/json"))) {
                response.finish(JBean.by(-2, "未登陆"));
            } else {
                //response.setStatus(302);
                response.setHeader("Content-Type", "text/html;charset=UTF-8");
                response.setHeader("location", "/user/login.html");
                response.finish304();
            }
            return;
        }
        super.authenticate(request, response);
    }

    @Override
    public void execute(HttpRequest request, HttpResponse response) throws IOException {
        try {
            // logger.log(Level.INFO, String.format("%s : %s", new Date(), request.getRequestURI()));
            super.execute(request, response);
        } catch (UnsupportedOperationException e) {
            e.printStackTrace();
            response.finish(JBean.by(-1, e.getMessage()));
        } catch (CfgException e) { // 系统元数据配置异常
            e.printStackTrace();
            System.out.println("-------------------------------------------");
            e.log(request);
            System.out.println("-------------------------------------------");
            response.finish(JBean.by(-1, e.getMessage()));
        }
    }
}
