import Resources from '../cgt/resources'
import Config from '../config'
import App from '../app'

export const drawResourcesItems = (ctx, items, x, y) => {
    ctx.fillStyle = '#000'
    ctx.font = '16px Lato'
    items.forEach((item, i) => {
        const offset_y = i * 35

        ctx.textAlign = 'right'
        ctx.fillText(item.value, x, y + 10 + offset_y)

        ctx.drawImage(item.icon, x + 10, y + offset_y, 20, 20)

        ctx.textAlign = 'left'
        ctx.fillText(item.label, x + 40, y + 10 + offset_y)
    })
}

export const drawResource = (ctx, type, x, y) => {
    const icon = Config.resources[type].icon
    const img = Resources.get(icon)
    ctx.drawImage(img, x, y, 20, 20)
}

export const makeResourceItem = (type, min, max = null) => {
    const value = max ? Math.max(0, (Math.random() * (max - min) + min).toFixed()) : min
    const res = Config.resources[type]
    return {
        type,
        value,
        icon: Resources.get(res.icon),
        label: res.title
    }
}

export const isMetRequirements = (player, neededResources, level = 0) => {
    const playerLevel = player.getResource('LEVEL').value
    if (playerLevel < level) return false

    const availableResources = player.getResources()
    const ok = neededResources.every(item => {
        const playerResource = availableResources.find(res => item.type === res.type)
        const playerResourceAmount = playerResource ? playerResource.value : 0
        return item.amount <= playerResourceAmount
    })

    return ok
}

export const processTact = (player, areas) => {
    const hasPlayerBuilding = area => area.getBuilding() && area.buildingOwner === player
    const areasWithBuildings = areas.filter(hasPlayerBuilding)

    const places = areasWithBuildings.reduce((result, area) => {
        const building = area.getBuilding()
        if (building.type === 'HOUSE') {
            if (building.level === 0) result += 3
            else if (building.level === 1) result += 6
            else if (building.level === 2) result += 9
        }
        return result
    }, 0)


    const resourcesCount = player.getResources().reduce((result, res) => {
        if (['FISH', 'ANIMALS', 'WHEAT'].indexOf(res.type)) {
            result += res.value
        }
        return result
    }, 0)

    const peopleCount = Math.max(3, Math.min(places, resourcesCount / 2))

    const peopleNeed = areasWithBuildings.reduce((result, area) => result + area.building.config.people, 0)
    player.setResourceAmount('PEOPLE', peopleCount - peopleNeed)

    let resToEat = peopleCount * 2
    player.getResources()
        .slice(0)
        .sort((a, b) => a.value === b.value ? 0 : (a.value > b.value) ? 1 : -1)
        .forEach(res => {
            if (['FISH', 'ANIMALS', 'WHEAT'].indexOf(res.type) >= 0) {
                const eat = Math.min(resToEat, res.value)
                resToEat -= eat
                player.setResourceAmount(res.type, res.value - eat)
            }
        })

    areasWithBuildings.sort(() => Math.random() - 0.5)
        .slice(0, peopleCount)
        .forEach(area => {
            const building = area.getBuilding()

            const multiplier = building.level == 0 ? 1 : (building == 1 ? 2 : 3)

            const convert = building.config.convert
            if (convert && convert.length) {
                if (isMetRequirements(player, convert)) {
                    player.increaseResources(convert, -1)
                    player.increaseResources([
                        {
                            type: building.config.produce,
                            amount: multiplier
                        }
                    ])
                }
            } else {
                const resForIncrease = area.resources
                    .filter(item => item.type === building.config.produce)
                    .map(item => {
                        return {
                            type: item.type,
                            amount: item.value * multiplier
                        }
                    })
                player.increaseResources(resForIncrease)
            }
        })
}

let steps = [ 'FORESTER', 'QUARRY', 'FARM', 'HOUSE', 'HOUSE', 'FISHER',
        'FORESTER', 'QUARRY', 'FISHER', 'STEAL', 'COAL', 'SAWMILL', 'FISHER',
    'FORGE', 'SAWMILL', 'FORGE', 'WIN' ]
export const scriptBot = (bot) => {
    const step = steps[0]

    if (!isMetRequirements(bot, App.Config.buildings[step].requirements[0])) {
        return false
    }

    const areas = App.getWorld().areas.filter(area => {
        return !area.getBuilding()
            && area.avalilableBuildings.indexOf(step) >= 0
    })

    if (!areas.length) {
        steps.shift()
        return false
    }

    const area = areas[ Math.floor( Math.random() * areas.length ) ]

    area.build(step, bot)
    steps.shift()

    return step === 'WIN'
}

export default {
    drawResourcesItems,
    makeResourceItem,
    isMetRequirements,
    drawResource,
    processTact,
    scriptBot
}
