package com.avg.zaap.crashlibrary.file.observer;

import android.os.FileObserver;

import com.avg.zaap.crashlibrary.core.logger.CrashLogger;

/**
 * This class serves as the extension of {@link FileObserver} with callback whenever a new file or
 * directory in the observed location is created.
 * <p>
 * Created by marek.osvald on 21.4.2016.
 */
public class FilePathObserver extends FileObserver {

    private static final String TAG = FilePathObserver.class.getSimpleName();
    private static final String PATTERN_FILE_EXTENSION = "\\.[^\\.]+$";

    private String mPath;
    private IFilePathObserverCallback mCallback;

    /**
     * Parametric constructor. Sets observed path, observation mask, callbacks and dependency
     * factory.
     *
     * @param mask     filter mask which filters the events
     * @param path     observed path
     * @param callback callback to notify {@link IFilePathObserverCallback} instance about a new file
     */
    public FilePathObserver(String path, @SuppressWarnings("SameParameterValue") int mask, IFilePathObserverCallback callback) {
        super(path, mask);
        mPath = path;
        mCallback = callback;
    }

    @Override
    public void onEvent(int event, final String fileName) {
        if (fileName == null) {
            CrashLogger.d(TAG, "Path has changed, but is NULL, event: ", event);
            return;
        }

        String absolutePath = mPath + fileName; // mPath ends with the file separator
        String crashCode = fileName.replaceFirst(PATTERN_FILE_EXTENSION, "");
        mCallback.onNewFileCreated(crashCode, absolutePath);
    }

}
