/* 
    This file is a part of the SteamWar software.
    
    Copyright (C) 2020  SteamWar.de-Serverteam

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero 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 Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/

package de.steamwar.velocitycore.commands;

import de.steamwar.command.SWCommand;
import de.steamwar.messages.Chatter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class WebpasswordCommand extends SWCommand {

    public WebpasswordCommand() {
        super("webpassword", "webpw", "web");
    }


    @Register(description = "WEB_USAGE")
    public void genericCommand(Chatter sender, String password) {
        if(password.length() < 8) {
            sender.system("WEB_PASSWORD_LENGTH");
            return;
        }

        ProcessBuilder pb = new ProcessBuilder("php", "/var/www/register.php", sender.user().getUserName(), password);
        pb.redirectErrorStream(true);
        try {
            Process regProcess = pb.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(regProcess.getInputStream()));
            String errorLine;
            if((errorLine = reader.readLine()) != null) {
                if ("updated".equals(errorLine)) {
                    sender.system("WEB_UPDATED");
                    return;
                } else {
                    throw new SecurityException("Could not create webaccount " + errorLine);
                }
            }

            sender.system("WEB_CREATED");
        } catch (IOException e) {
            throw new SecurityException("Could not create webaccount", e);
        }
    }

    public static void changeUsername(String oldUsername, String newUsername){
        ProcessBuilder pb = new ProcessBuilder("php", "/var/www/changename.php", oldUsername, newUsername);
        try {
            pb.start();
        } catch (IOException e) {
            throw new SecurityException("Could not change username", e);
        }
    }
}
