#!/usr/bin/python3

# Copyright © 2013 Jakub Wilk <jwilk@jwilk.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the “Software”), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

import os
import sys

basedir = os.path.join(
    os.path.dirname(__file__),
    os.pardir,
)
sys.path[:0] = [basedir]

from lib import encodings
from lib import iconv

def generate_charmap(encoding):
    encoding = encoding.upper()
    print(encoding, '...', end=' ')
    sys.stdout.flush()
    path = '{base}/data/charmaps/{enc}'.format(base=basedir, enc=encoding)
    n = 0
    us = []
    for b in range(0x100):
        b = bytes([b])
        try:
            u = iconv.decode(b, encoding)
        except UnicodeDecodeError:
            u = '\uFFFE'
        else:
            n += 1
        assert len(u) == 1
        us += [u]
    if n <= 128:
        print('SKIP (not 8-bit)')
        return
    assert len(us) == 0x100
    with open(path, 'wb') as file:
        us = ''.join(us)
        assert len(us) == 0x100
        file.write(us.encode('UTF-8'))
    print('ok')

def main():
    for encoding, codec in encodings._portable_encodings.items():
        if codec is None:
            generate_charmap(encoding)
    for encoding in encodings._extra_encodings:
        generate_charmap(encoding)

if __name__ == '__main__':
    main()

# vim:ts=4 sw=4 et
