#include <daguerre/psf.hpp>

namespace daguerre {

  //TODO: this assumes the font is in psf2 format, and has a unicode table
  std::optional<fixed_font<bool>> try_load_psf(FILE *input) {

    uint32_t header[8];
    if (fread(header, 4, 8, input) != 8)
      return {};

    const uint32_t glyphs_start = header[2];
    const uint32_t glyph_count = header[4];
    const uint32_t glyph_length = header[5];
    const uint32_t height = header[6];
    const uint32_t width = header[7];

    fixed_font<bool> font(width, height);

    const uint32_t unicode_start = glyphs_start + glyph_count * glyph_length;
    fseek(input, unicode_start, SEEK_SET);

    uint32_t indices[128];

    for (uint32_t index = 0; index < glyph_count; ++index) {
      uint8_t ch;
      fread(&ch, 1, 1, input);
      if (ch < 128)
        indices[ch] = index;
      do
        if (fread(&ch, 1, 1, input) != 1)
          return {};
      while (ch != 0xff);
    }

    for (uint8_t ch = 0; ch < 128; ++ch) {
      fseek(input, glyphs_start + glyph_length * indices[ch], SEEK_SET);
      for (unsigned h = 0; h < height; ++h)
        for (unsigned wb = 0; wb < width; wb += 8) {
          uint8_t byte;
          fread(&byte, 1, 1, input);
          for (unsigned x = 0; x < 8 && wb + x < width; ++x)
            font.glyphs[ch].at(wb + x, h) = (byte >> (7 - x)) & 1;
        }
    }

    return font;

  }

}
