001/*
002 * Copyright (C) Photon Vision.
003 *
004 * This program is free software: you can redistribute it and/or modify
005 * it under the terms of the GNU General Public License as published by
006 * the Free Software Foundation, either version 3 of the License, or
007 * (at your option) any later version.
008 *
009 * This program is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
012 * GNU General Public License for more details.
013 *
014 * You should have received a copy of the GNU General Public License
015 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
016 */
017
018package org.photonvision.common.configuration;
019
020import java.io.File;
021import java.nio.file.Path;
022import java.text.DateFormat;
023import java.text.ParseException;
024import java.text.SimpleDateFormat;
025import java.time.LocalDateTime;
026import java.time.format.DateTimeFormatter;
027import java.time.temporal.TemporalAccessor;
028import java.util.Date;
029
030public class PathManager {
031    private static PathManager INSTANCE;
032
033    final File configDirectoryFile;
034
035    public static PathManager getInstance() {
036        if (INSTANCE == null) {
037            INSTANCE = new PathManager();
038        }
039        return INSTANCE;
040    }
041
042    private PathManager() {
043        this.configDirectoryFile = new File(getRootFolder().toUri());
044    }
045
046    public Path getRootFolder() {
047        return Path.of("photonvision_config");
048    }
049
050    public Path getLogsDir() {
051        return Path.of(configDirectoryFile.toString(), "logs");
052    }
053
054    public static final String LOG_PREFIX = "photonvision-";
055    public static final String LOG_EXT = ".log";
056    public static final String LOG_DATE_TIME_FORMAT = "yyyy-M-d_hh-mm-ss";
057
058    public String taToLogFname(TemporalAccessor date) {
059        var dateString = DateTimeFormatter.ofPattern(LOG_DATE_TIME_FORMAT).format(date);
060        return LOG_PREFIX + dateString + LOG_EXT;
061    }
062
063    public Path getLogPath() {
064        var logFile = Path.of(this.getLogsDir().toString(), taToLogFname(LocalDateTime.now())).toFile();
065        if (!logFile.getParentFile().exists()) logFile.getParentFile().mkdirs();
066        return logFile.toPath();
067    }
068
069    public Date logFnameToDate(String fname) throws ParseException {
070        // Strip away known unneeded portions of the log file name
071        fname = fname.replace(LOG_PREFIX, "").replace(LOG_EXT, "");
072        DateFormat format = new SimpleDateFormat(LOG_DATE_TIME_FORMAT);
073        return format.parse(fname);
074    }
075}