package com.lemon.lifecenter.common;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mobile.device.Device;
import org.springframework.mobile.device.DeviceUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

@Component
public class LifeCenterInterCeptor extends HandlerInterceptorAdapter {
    @Autowired
    private LifeCenterConfigVO config;
    
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        System.out.println("--------------------- InterCeptor Start --------------------- ");

        String url = request.getRequestURI().toString();
        String port = String.valueOf(request.getLocalPort());
        Device device = DeviceUtils.getCurrentDevice(request);

        logger.info("IP : " + LifeCenterFunction.getRemoteAddr(request) + " URL : " + url + " Port : " + port + " Device : " + device );
        
        Object session = request.getSession().getAttribute( "sesId" );
        
        if( !url.equals( "/login/staff" ) && !url.equals( "/login/admin" ) && !url.equals( "/login/check" ) ) {
            if( session == null ) {
                response.sendRedirect( "/login/staff" );
                return false;
            } else {
                logger.info( "IP : " + LifeCenterFunction.getRemoteAddr( request ) + " ID : " + session.toString() + "  URL : " + url + " Port : " + port );
            }
            
        } else if( url.equals( "/login/staff" ) || url.equals( "/login/admin" ) ) {
            if( session != null ) {
                response.sendRedirect( "/patient/list" );
                return false;
            }
            
        }
        
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) {
        //logger.info("Method Executed Time : postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
            Exception ex) {
        //logger.info("Method Completed Time : afterCompletion");
        System.out.println("--------------------- InterCeptor afterCompletion ---------------------");
    }
}
