'use strict'

import stringifyFont from 'css-font/stringify'
const defaultChars = [32, 126]

export function fontAtlas(options) {
    options = options || {}

    let shape = options.shape
        ? options.shape
        : options.canvas
        ? [options.canvas.width, options.canvas.height]
        : [512, 512]
    const canvas = options.canvas || document.createElement('canvas')
    let font = options.font
    const step =
        typeof options.step === 'number'
            ? [options.step, options.step]
            : options.step || [32, 32]
    let chars = options.chars || defaultChars

    if (font && typeof font !== 'string') font = stringifyFont(font)

    if (!Array.isArray(chars)) {
        chars = String(chars).split('')
    } else if (
        chars.length === 2 &&
        typeof chars[0] === 'number' &&
        typeof chars[1] === 'number'
    ) {
        const newchars = []

        for (let i = chars[0], j = 0; i <= chars[1]; i++) {
            newchars[j++] = String.fromCharCode(i)
        }

        chars = newchars
    }

    shape = shape.slice()
    canvas.width = shape[0]
    canvas.height = shape[1]

    const ctx = canvas.getContext('2d')

    ctx.fillStyle = '#fff'
    ctx.fillRect(0, 0, canvas.width, canvas.height)

    ctx.font = font
    ctx.textAlign = 'center'
    ctx.textBaseline = 'middle'
    ctx.fillStyle = options.color || '#000'

    let x = step[0] / 2
    let y = step[1] / 2
    for (let i = 0; i < chars.length; i++) {
        ctx.fillText(chars[i], x, y)
        if ((x += step[0]) > shape[0] - step[0] / 2)
            (x = step[0] / 2), (y += step[1])
    }

    return canvas
}
