/*
 * Copyright (C) 2019-2021 Eugene 'Vindex' Stulin
 *
 * mediafragmenter is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import amalthea.fileformats,
       amalthea.langlocal;
import std.file,
       std.getopt,
       std.path,
       std.range,
       std.string;

import fragpointer_module;

immutable app = "mediafragmenter";
immutable string shareDir;
immutable string helpDir;

shared static this() {
    initLocalization(translations);
    string currentApp = readLink("/proc/self/exe");
    shareDir = buildNormalizedPath(dirName(currentApp), "..", "share");
    helpDir = shareDir ~ "/help/";
}


void showHelp() {
    immutable lang = getSystemLanguage();
    string pathToHelpFile = helpDir ~ lang ~ "/" ~ app ~ "/help.txt";
    if (!exists(pathToHelpFile)) {
        pathToHelpFile = helpDir ~ "en_US/" ~ app ~ "/help.txt";
    }
    writeln(readText(pathToHelpFile));
}


int main(string[] args) { try {
    if (args.length == 2 && args[1] == "--version") {
        fragpointer_module.showVersion();
        return 0;
    }
    if (args.length == 2 && args[1] == "--help") {
        showHelp();
        return 0;
    }
    
    string filepath;
    string outputFile;
    string start, finish;
    string type;
    args.getopt(config.passThrough, "start|s",  &start,
                                    "finish|f", &finish,
                                    "type|t",   &type,
                                    "output|o", &outputFile);
    if (args.length != 2) {
        stderr.writefln("%s %s",
            "Wrong using of mediafragmenter."._s,
            "See: mediafragmenter --help"._s);
        return 1;
    }
    filepath = args[1];

    
    if (type.empty) {
        if (filepath.exists && filepath.isFile) {
            type = getFileFormat(filepath).group.toLower;
        } else {
            stderr.writeln("No such file."._s);
            return 2;
        }
    }

    MediaType mediaType;
    try {
        mediaType = to!MediaType(type);
        if (!start.empty)  checkPointerValidity(mediaType, start);
        if (!finish.empty) checkPointerValidity(mediaType, finish);
    } catch (ConvException e) {
        stderr.writefln("%s: %s", type, "Invalid format of the file."._s);
        return 3;
    } catch(InvalidFragPointer e) {
        stderr.writeln(e.msg);
        return 3;
    }

    string dataOfFragPointer;
    dataOfFragPointer ~= "Type: " ~ type ~ "\n";
    dataOfFragPointer ~= "Path: " ~ filepath ~ "\n";
    dataOfFragPointer ~= "Start: " ~ start ~ "\n";
    dataOfFragPointer ~= "Finish: " ~ finish ~ "\n";

    if (outputFile.empty) {
        outputFile = filepath.stripExtension ~ ".fragpointer";
    }
    std.file.write(outputFile, dataOfFragPointer);

} catch (Exception e) {
    stderr.writeln(e.msg);
    return 9;
} 
    return 0;
}


immutable translations = [
    ["en_US", "ru_RU", "eo"],
    [
        "Wrong using of mediafragmenter.",
        "Неправильное использование mediafragmenter.",
        "Neregula uzado de mediafragmenter."
    ],
    [
        "See: mediafragmenter --help",
        "Смотрите: mediafragmenter --help",
        "Rigardu: mediafragmenter --help"
    ],
    [
        "No such file.",
        "Нет такого файла.",
        "Ĉi tiu dosiero ne ekzistas."
    ],
    [
        "Invalid format of the file.",
        "Неподходящий формат файла.",
        "Nekonvena datenaranĝo de la dosiero."
    ]
];
