package ctbrec.recorder.postprocessing;

import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;

import java.io.File;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.junit.Test;

import ctbrec.Config;
import ctbrec.Model;
import ctbrec.Recording;

public class MoveSingleFileTest extends AbstractPpTest {

    @Test
    public void testOriginalFileReplacement() throws IOException {
        Config config = mockConfig();
        Recording rec = new Recording();
        rec.setModel(mockModel());
        rec.setAbsoluteFile(original);
        rec.setStartDate(now);
        rec.setSingleFile(true);

        Move pp = new Move();
        pp.getConfig().put(Move.PATH_TEMPLATE, new File(baseDir.toFile(), Move.DEFAULT).getAbsolutePath());
        pp.postprocess(rec, recordingManager, config);

        Matcher m = Pattern.compile(baseDir.toFile() + "/Mockita_Boobilicious/\\d{4}-\\d{2}-\\d{2}_\\d{2}-\\d{2}-\\d{2}/original\\.ts").matcher(rec.getAbsoluteFile().toString());
        assertTrue(m.matches());
        assertEquals(rec.getAbsoluteFile(), rec.getPostProcessedFile());
        assertNotEquals(rec.getAbsoluteFile(), original);
    }

    @Test
    public void testEarlyExit() throws IOException {
        Model model = mockModel();
        Recording rec = mock(Recording.class);
        when(rec.getModel()).thenReturn(model);
        when(rec.getAbsoluteFile()).thenReturn(original);
        when(rec.getPostProcessedFile()).thenReturn(original);
        when(rec.getStartDate()).thenReturn(now);
        doThrow(new RuntimeException("Unexpected call of setAbsoluteFile")).when(rec).setAbsoluteFile(any());
        Move pp = new Move();
        Config config = mockConfig();
        pp.getConfig().put(Move.PATH_TEMPLATE, original.getParentFile().getCanonicalPath());
        pp.postprocess(rec, recordingManager, config);
    }

    @Test
    public void absoluteFileShouldKeepBeingOriginalIfFilesDiffer() throws IOException {
        Model model = mockModel();
        Recording rec = mock(Recording.class);
        when(rec.getModel()).thenReturn(model);
        when(rec.getAbsoluteFile()).thenReturn(original);
        when(rec.getPostProcessedFile()).thenReturn(postProcessed);
        when(rec.getStartDate()).thenReturn(now);
        doThrow(new RuntimeException("Unexpected call of setAbsoluteFile")).when(rec).setAbsoluteFile(any());
        Move pp = new Move();
        Config config = mockConfig();
        pp.getConfig().put(Move.PATH_TEMPLATE, new File(baseDir.toFile(), Move.DEFAULT).getAbsolutePath());
        pp.postprocess(rec, recordingManager, config);
    }

    @Test
    public void testToString() {
        Move pp = new Move();
        assertEquals("move", pp.toString());

        pp.getConfig().put(Move.PATH_TEMPLATE, Move.DEFAULT);
        assertEquals("move ["+Move.DEFAULT+"]", pp.toString());
    }
}
