package cn.yunzhixue.ability.center.examsprint.infrastructure.report.pdf;

import org.junit.jupiter.api.Test;

import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.Locale;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

class BundledOutlookReportFontsTest {

    @Test
    void loadReturnsCachedInstanceWithOneMiSansRegistrationWhenHealthy() {
        BundledOutlookReportFonts first = BundledOutlookReportFonts.load();
        BundledOutlookReportFonts second = BundledOutlookReportFonts.load();

        assertThat(second).isSameAs(first);
        assertThat(first.registrations()).hasSize(1);
        BundledOutlookReportFonts.Registration registration = first.registrations().get(0);
        assertThat(registration.family()).isEqualTo("MiSans");
        assertThat(registration.file().getName()).isEqualTo("MiSans-VF.ttf");
        assertThat(registration.file()).exists().isFile().canRead();
        assertThat(registration.file().length()).isGreaterThan(0L);
    }

    @Test
    void loadRegistersBundledMiSansWithAwtGraphicsEnvironmentForBatikSvgText() {
        BundledOutlookReportFonts.load();

        String[] availableFontFamilies = GraphicsEnvironment.getLocalGraphicsEnvironment()
                .getAvailableFontFamilyNames(Locale.ROOT);

        assertThat(Arrays.asList(availableFontFamilies)).contains("MiSans VF");
        assertThat(new Font("MiSans VF", Font.PLAIN, 24).canDisplayUpTo("掌握率")).isEqualTo(-1);
    }

    @Test
    void loadRecreatesTempCopyWhenCachedFileIsRemoved() throws Exception {
        BundledOutlookReportFonts first = BundledOutlookReportFonts.load();
        BundledOutlookReportFonts.Registration firstRegistration = first.registrations().get(0);
        Files.delete(firstRegistration.file().toPath());

        BundledOutlookReportFonts second = BundledOutlookReportFonts.load();
        BundledOutlookReportFonts.Registration secondRegistration = second.registrations().get(0);

        assertThat(secondRegistration.family()).isEqualTo("MiSans");
        assertThat(secondRegistration.file().getName()).isEqualTo("MiSans-VF.ttf");
        assertThat(secondRegistration.file()).exists().isFile().canRead();
        assertThat(secondRegistration.file().length()).isGreaterThan(0L);
    }

    @Test
    void loadFailsWithClearMessageWhenClasspathResourceIsMissing() {
        assertThatThrownBy(() -> BundledOutlookReportFonts.load("/fonts/does-not-exist.ttf"))
                .isInstanceOf(BundledOutlookReportFonts.BundledFontMissingException.class)
                .hasMessageContaining("/fonts/does-not-exist.ttf")
                .hasMessageContaining("Bundled font resource not found on classpath");
    }
}
