<commit_before>/*
 *    Copyright 2019 <NAME> (Panzer1119)
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package de.codemakers.chat.connector;

import de.codemakers.base.exceptions.CJPException;
import de.codemakers.base.logger.Logger;
import de.codemakers.chat.Main;
import de.codemakers.chat.entities.User;
import de.codemakers.chat.gui.ChatTab;
import de.codemakers.io.file.AdvancedFile;

import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;

public class FileChat<U extends User> extends Chat<U> {
    
    public static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss"); //TODO Temp only
    
    protected final AdvancedFile advancedFile;
    protected boolean started = false;
    protected BufferedWriter bufferedWriter = null;
    protected Timer timer = null;
    
    public FileChat(ChatTab chatTab, U selfUser, AdvancedFile advancedFile) {
        super(chatTab, selfUser);
        Objects.requireNonNull(advancedFile);
        this.advancedFile = advancedFile;
        Main.EXIT_HOOKS.add(() -> {
            stop();
            close();
        }); //FIXME Only for testing?
    }
    
    public boolean isStarted() {
        return started;
    }
    
    public AdvancedFile getAdvancedFile() {
        return advancedFile;
    }
    
    protected void update() throws Exception {
        final String text_old = chatTab.getEditorPane().getText();
        final String text_new = new String(advancedFile.readBytes());
        if (!Objects.equals(text_old, text_new)) {
            chatTab.getEditorPane().setText(text_new);
            scrollEditorPaneToBottom();
        }
    }
    
    @Override
    public boolean send(Object message, Object... arguments) throws Exception {
        if (!started) {
            throw new CJPException("Not started");
        }
        Instant instant = Instant.now();
        if (arguments.length >= 1 && arguments[0] instanceof Instant) {
            instant = (Instant) arguments[0];
        }
        final String temp = String.format("[%s] %s: %s", LocalDateTime.ofInstant(instant, ZoneId.systemDefault()).format(DATE_TIME_FORMATTER), getSelfUser().toDisplayString(), message);
        bufferedWriter.write(temp);
        bufferedWriter.newLine();
        bufferedWriter.flush();
        return true;
    }
    
    @Override
    public boolean start() throws Exception {
        if (started) {
            return false;
        }
        if (!advancedFile.exists()) {
            if (!advancedFile.createNewFile()) {
                throw new FileNotFoundException(advancedFile.getAbsolutePath() + " could not be created");
            }
        }
        bufferedWriter = advancedFile.createBufferedWriter(true); //TODO Maybe do not append?
        timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override<commit_msg>Created preSend() method in FileChat.java to edit the bytes that will be "send" to the file before they will be written to it<commit_after>/*
 *    Copyright 2019 <NAME> (Panzer1119)
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package de.codemakers.chat.connector;

import de.codemakers.base.exceptions.CJPException;
import de.codemakers.base.logger.Logger;
import de.codemakers.chat.Main;
import de.codemakers.chat.entities.User;
import de.codemakers.chat.gui.ChatTab;
import de.codemakers.io.file.AdvancedFile;

import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;

public class FileChat<U extends User> extends Chat<U> {
    
    public static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss"); //TODO Temp only
    
    protected final AdvancedFile advancedFile;
    protected boolean started = false;
    protected BufferedWriter bufferedWriter = null;
    protected Timer timer = null;
    
    public FileChat(ChatTab chatTab, U selfUser, AdvancedFile advancedFile) {
        super(chatTab, selfUser);
        Objects.requireNonNull(advancedFile);
        this.advancedFile = advancedFile;
        Main.EXIT_HOOKS.add(() -> {
            stop();
            close();
        }); //FIXME Only for testing?
    }
    
    public boolean isStarted() {
        return started;
    }
    
    public AdvancedFile getAdvancedFile() {
        return advancedFile;
    }
    
    protected void update() throws Exception {
        final String text_old = chatTab.getEditorPane().getText();
        final String text_new = new String(advancedFile.readBytes());
        if (!Objects.equals(text_old, text_new)) {
            chatTab.getEditorPane().setText(text_new);
            scrollEditorPaneToBottom();
        }
    }
    
    @Override
    public boolean send(Object message, Object... arguments) throws Exception {
        if (!started) {
            throw new CJPException("Not started");
        }
        Instant instant = Instant.now();
        if (arguments.length >= 1 && arguments[0] instanceof Instant) {
            instant = (Instant) arguments[0];
        }
        final String temp = String.format("[%s] %s: %s", LocalDateTime.ofInstant(instant, ZoneId.systemDefault()).format(DATE_TIME_FORMATTER), getSelfUser().toDisplayString(), message);
        bufferedWriter.write(new String(preSend(temp.getBytes())));
        bufferedWriter.newLine();
        bufferedWriter.flush();
        return true;
    }
    
    protected byte[] preSend(byte[] data) throws Exception {
        return data;
    }
    
    @Override
    public boolean start() throws Exception {
        if (started) {
            return false;
        }
        if (!advancedFile.exists()) {
            if (!advancedFile.createNewFile()) {
                throw new FileNotFoundException(advancedFile.getAbsolutePath() + " could not be created");
            }
        }
        bufferedWriter = advancedFile.createBufferedWriter(true); //TODO Maybe do not append?
        timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
{'fraction_non_alphanumeric': 0.09789376076301497, 'fraction_numerical': 0.003974036296198172, 'mean_word_length': 2.842239185750636, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2492901', 'n_tokens_mistral': 2073, 'n_tokens_neox': 2014, 'n_words': 578}