import res from '../../cgt/resources'
import config from '../../config'

let maptiles = null
let person = null
const init = () => {
    maptiles = res.get('mapitems')
    person = res.get('person')
}

const mapScreenCellsX = 20
const mapScreenCellsY = 18

const mapCellSizeX = 8
const mapCellSizeY = 8

const getCell = (x, y) => {
    const n = config.map().get(x, y)
    return n === null ? null : {
        x: (n % 10) * mapCellSizeX,
        y: ~~(n / 10) * mapCellSizeY,
        w: mapCellSizeX,
        h: mapCellSizeY
    }
}

let pOffset = { x: 0, y: 0 }
const setPlayerOffset = offset => {
    pOffset = offset
}

const drawSprite = (ctx) => {
    ctx.drawImage(
        person,
        (config.player().dir - 1) * 8, 0, 8, 8,
        10 * 8, 9 * 8, 8, 8
    )
}

const render = (ctx) => {
    for (let y = -1; y < mapScreenCellsY + 2; y++) {
        for (let x = -1; x < mapScreenCellsX + 2; x++) {
            const cellX = x + config.player().position.x - 10
            const cellY = y + config.player().position.y - 9
            const cell = getCell(cellX, cellY)
            if (cell != null) {
                ctx.drawImage(
                    maptiles,
                    cell.x, cell.y, cell.w, cell.h,
                    x * mapCellSizeX - pOffset.x, y * mapCellSizeY - pOffset.y,
                    mapCellSizeX, mapCellSizeY
                )
            }
        }
    }

    drawSprite(ctx)
}

export default {
    init,
    render,
    setPlayerOffset
}
