import { makeResourceItem } from './helpers'
import Resources from '../cgt/resources'
import Building from './building'

import App from '../app'

export default class Area {
    constructor(data) {
        this.title = data.title
        this.images = data.images.map(item => {
            return {
                img: Resources.get(item.src),
                x: -70,
                y: item.y,
                w: 140,
                h: item.h
            }
        })
        this.resources = data.resources
            .map(item => makeResourceItem(item.type, item.min, item.max))
            .filter(item => item.value > 0)

        this.avalilableBuildings = data.buildings

        this.building = null
        this.buildingOwner = null
    }

    update() {}

    draw(ctx, withResources = true) {
        this.images.forEach(item => {
            ctx.drawImage(item.img, item.x, item.y, item.w, item.h)
        })

        let produce = null
        let ownerColor = ''

        if (this.building) {
            this.building.draw(ctx)
            produce = this.building.config.produce
            ownerColor = this.buildingOwner === App.Player ? 'green' : 'red'

            ctx.beginPath()
            ctx.fillStyle = ownerColor
            ctx.arc(0, 10, 2, 0, 2 * Math.PI)
            ctx.fill()
        }

        if (withResources) {
            this.resources.forEach((item, i) => {
                const offset_y = i * 25 + 10

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

                ctx.fillStyle = '#000'
                ctx.font = '16px Lato'
                ctx.textAlign = 'left'
                ctx.fillText(item.value, 10, 20 + offset_y)

                if (produce === item.type) {
                    ctx.strokeStyle = ownerColor
                    ctx.strokeRect(-60, offset_y + 7, 120, 26)
                }
            })
        }
    }

    info() {
        return {
            title: this.title,
            resources: this.resources
        }
    }

    getBuilding() {
        return this.building
    }

    removeBuilding() {
        this.building = null
    }

    upgradeBuilding() {
        this.building.level++
    }

    getAvalilableBuildings() {
        return this.avalilableBuildings
    }

    build(type, owner) {
        this.building = new Building(type)
        this.buildingOwner = owner
    }
}
