/*
 * Copyright (c) 2004 Brian McCallister. All Rights Reserved.
 */
package org.skife.gear.service;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.skife.gear.ServiceException;
import org.skife.gear.Student;

import javax.servlet.ServletContext;
import java.io.File;
import java.io.IOException;

public class StudentIndexer
{
    /**
     * Can change to servlet init param if ever need to
     */
    public static final String SERVLET_INDEX = "WEB-INF/student-index";
    public static final String NAME = "name";
    public static final String ID_NUMBER = "id";
    public static final String IDENTITY = "pk";
    public static final String ADDRESS = "address";
    public static final String PHONE = "phone";
    final File index;

    private final static Object mutex = new Object();
    private final Analyzer analyzer;

    public StudentIndexer(final Analyzer analyzer, final String dir) throws IOException
    {
        this.analyzer = analyzer;
        index = new File(dir);
        if (!index.exists())
        {
            index.mkdir();
            synchronized (mutex)
            {
                final IndexWriter writer = new IndexWriter(index, new StandardAnalyzer(), true);
                writer.close();
            }
        }
    }

    public StudentIndexer(final String dir) throws IOException
    {
        this(new org.skife.gear.search.SmarterAnalyzer(), dir);
    }

    public StudentIndexer(final ServletContext ctx) throws IOException
    {
        this(new org.skife.gear.search.SmarterAnalyzer(), ctx.getRealPath(SERVLET_INDEX));
    }

    public void add(final Student student) throws ServiceException
    {
        final Document doc = new Document();
        doc.add(Field.Text(NAME, student.getName()));
        doc.add(Field.Text(ID_NUMBER, student.getIdNumber()));
        doc.add(Field.Text(ADDRESS, student.getAddress()));
        doc.add(Field.Text(PHONE, student.getPhone()));
        doc.add(Field.UnIndexed(IDENTITY, student.getId().toString()));
        try
        {
            synchronized (mutex)
            {
                final IndexWriter writer = new IndexWriter(index, analyzer, false);
                writer.addDocument(doc);
                writer.optimize();
                writer.close();
            }
        }
        catch (IOException e)
        {
            throw new ServiceException("Unable to index student", e);
        }
    }
}

