/*
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2013 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 * --------------------------------------------------------------------------
 *  $Id$
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.shell.internal;

import java.io.File;

import javax.security.auth.Subject;

import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Instantiate;
import org.apache.felix.ipojo.annotations.Provides;
import org.apache.felix.ipojo.annotations.StaticServiceProperty;
import org.apache.felix.ipojo.annotations.Validate;
import org.ow2.jonas.lib.bootstrap.JProp;
import org.ow2.shelbie.core.history.HistoryFileProvider;

/**
 * @author Loic Albertin
 */
@Component(immediate = true, name = "JOnAS-SHB-HistoryFileProvider")
@Instantiate
@Provides(properties = {@StaticServiceProperty(name = "service.ranking", value = "50", type = "java.lang.Integer")})
public class JOnASHistoryFileProvider implements HistoryFileProvider {

    private File historyWorkFile;

    @Validate
    private void startup() {
        File workDir = new File(JProp.getInstance().getWorkDirectory());
        historyWorkFile = new File(workDir, "shelbie.history");
        if (!historyWorkFile.exists()) {
            if (!historyWorkFile.mkdirs()) {
                throw new IllegalStateException("Could not create directory: " + historyWorkFile.getAbsolutePath());
            }
        } else if (!historyWorkFile.isDirectory()) {
            throw new IllegalStateException(historyWorkFile.getAbsolutePath() + " should be a directory.");
        }
    }

    @Override
    public File getHistoryFile(Subject subject) {
        return new File(historyWorkFile, String.valueOf(subject));
    }
}
