package com.cpic.telsale.SessionListener;

/**
 * Created by Kane on 2017/3/27.
 */
import javax.servlet.ServletContext;
import javax.servlet.http.*;
import java.io.File;
import java.io.IOException;

import com.cpic.util.FileTools;


public class SessionListener implements HttpSessionListener
{
    @Override
    public void sessionCreated( HttpSessionEvent event )
    {
        HttpSession session = event.getSession();
        ServletContext context = session.getServletContext();

        String sessionID = session.getId();
        String tempPathRoot = context.getRealPath( context.getInitParameter( "临时文件根目录" ) );
        String sessionTempPath = tempPathRoot + "/" + sessionID;

        File tempDir = new File( sessionTempPath );

        if ( !tempDir.exists() )
        {
            if ( tempDir.mkdirs() == true )
            {
                session.setAttribute( "临时文件根目录", sessionTempPath );
            }
            else
            {
                session.removeAttribute( "临时文件根目录" );
            }
        }
    }

    @Override
    public void sessionDestroyed( HttpSessionEvent event )
    {
        String tempPath = ( String ) event.getSession().getAttribute( "临时文件根目录" );

        if ( tempPath == null )
        {
            return;
        }

        File tempDir = new File( tempPath );

        if ( !tempDir.exists() )
        {
            return;
        }

        //删掉临时目录
        try
        {
            FileTools.deleteDirectory( tempPath );
        }
        catch( IOException error )
        {
            event.getSession().getServletContext().log( "删除“临时文件根目录”出错！" );
        }
    }
}
