import { Scene } from 'phaser'
import { fetchChatRoles } from '@/api'
import { emitter } from '@/plugins'

enum Direction {
    LEFT = 'l',
    RIGHT = 'r',
    UP = 'u',
    DOWN = 'd'
}
interface Path {
    postion: {
        x: number
        y: number
    }
    directions: Array<Direction>
}
interface Person {
    wait: boolean
    sprite: null | any
    paths: Array<Path>
    chatRole?: null | any
}

function getRandom(num = 1) {
    return Math.floor(Math.random() * num)
}

export default class PlayScene2 extends Scene {
    animatedTiles: any
    constructor() {
        super({ key: 'PlayScene2' })
    }
    private map: any
    private enterBtn: any
    private personInfo = <any>{
        Maria_Lopez: <Person>{
            wait: false,
            sprite: null,
            paths: []
        },
        Latoya_Williams: <Person>{
            wait: false,
            sprite: null,
            paths: []
        },
        Cactus: <Person>{
            wait: false,
            sprite: null,
            paths: []
        },
        Cowboy: <Person>{
            wait: false,
            sprite: null,
            paths: []
        },
        Coffin: <Person>{
            wait: false,
            sprite: null,
            paths: []
        },
        Coyote: <Person>{
            wait: false,
            sprite: null,
            paths: []
        },
        Rajiv_Patel: <Person>{
            wait: false,
            sprite: null,
            paths: []
        },
        Isabella_Rodriguez: <Person>{
            wait: false,
            sprite: null,
            paths: []
        },
        Arthur_Burton: <Person>{
            wait: false,
            sprite: null,
            paths: []
        },
        Tamara_Taylor: <Person>{
            wait: false,
            sprite: null,
            paths: []
        },
        Abigail_Chen: <Person>{
            wait: false,
            sprite: null,
            paths: []
        },
        Klaus_Mueller: <Person>{
            wait: false,
            sprite: null,
            paths: []
        },
        Wolfgang_Schulz: <Person>{
            wait: false,
            sprite: null,
            paths: []
        },
        Carlos_Gomez: <Person>{
            wait: false,
            sprite: null,
            paths: []
        },
        Giorgio_Rossi: <Person>{
            wait: false,
            sprite: null,
            paths: []
        },
        Carmen_Ortiz: <Person>{
            wait: false,
            sprite: null,
            paths: []
        },
        Ayesha_Khan: <Person>{
            wait: false,
            sprite: null,
            paths: []
        },
        Jennifer_Moore: <Person>{
            wait: false,
            sprite: null,
            paths: []
        },
        Jane_Moreno: <Person>{
            wait: false,
            sprite: null,
            paths: []
        },
        Francisco_Lopez: <Person>{
            wait: false,
            sprite: null,
            paths: []
        }
    }
    create() {
        this.add.tileSprite(0, 0, 2048, 1024, 'shadi').setOrigin(0, 0)
        this.map = this.make.tilemap({
            key: 'map2',
            tileWidth: 16,
            tileHeight: 16
        })
        console.log(this.map)
        const Atlas = this.map.addTilesetImage('Atlas', 'Atlas')
        this.map.createLayer('bg', [Atlas], 0, 0)
        this.map.createLayer('wall', [Atlas], 0, 0)
        this.map.createLayer('house', [Atlas], 0, 0)

        this.map.createLayer('dress', [Atlas], 0, 0)
        this.map.createLayer('sign', [Atlas], 0, 0)

        // console.log(this.personInfo)

        const width = (Math.floor(window.innerHeight / 100) - 6) * 50 + 2270
        this.cameras.main.setBounds(0, 0, width, 1024)
        this.cameras.main.fadeIn(1000)
        setTimeout(() => {
            this.cameras.main.pan(650, 512, 300)
            this.personInfo = {}

            fetchChatRoles(20).then((res: any) => {
                res.forEach((item: any) => {
                    this.personInfo[item.id] = <Person>{
                        wait: false,
                        sprite: null,
                        paths: [],
                        chatRole: item
                    }
                })

                this.setPerson()
            })
        }, 1000)

        // this.cameras.main.fadeIn(1000)

        // this.cameras.main.once('camerapancomplete', (camera: any) => {
        //     camera.pan(620, 512)
        // })

        const cam = this.cameras.main
        this.input.on('pointermove', (p: any) => {
            if (!p.isDown) return

            cam.scrollX -= (p.x - p.prevPosition.x) / cam.zoom
            // if (cam.scrollX < -220) {
            //     cam.scrollX = -220
            // }
            // if (cam.scrollX > 1290) {
            //     cam.scrollX = 1290
            // }
        })
    }

    update() {
        Object.keys(this.personInfo).forEach((key: string) => {
            const info = this.personInfo[key]
            if (info.sprite) {
                if (!info.wait) {
                    switch (info.direction) {
                        case 'l':
                            info.sprite.x -= 1
                            break
                        case 'r':
                            info.sprite.x += 1
                            break
                        case 'u':
                            info.sprite.y -= 1
                            break
                        case 'd':
                            info.sprite.y += 1
                            break
                    }
                    const walkName = {
                        [Direction.LEFT]: info.chatRole.playerName + '-left-walk',
                        [Direction.RIGHT]: info.chatRole.playerName + '-right-walk',
                        [Direction.UP]: info.chatRole.playerName + '-up-walk',
                        [Direction.DOWN]: info.chatRole.playerName + '-down-walk'
                    }
                    const x = info.sprite.x
                    const y = info.sprite.y
                    info.paths.forEach((path: Path) => {
                        if (x === path.postion.x && y === path.postion.y) {
                            const direction = path.directions[getRandom(path.directions.length)]
                            info.sprite.play(walkName[direction], true)
                            info.direction = direction
                        }
                    })
                }
            }
        })
    }

    setPerson() {
        Object.keys(this.personInfo).forEach((key: string, index: number) => {
            this.personInfo[key].paths = [...this.map.objects][index].objects.map((obj: any) => {
                return {
                    postion: {
                        x: obj.x,
                        y: obj.y
                    },
                    directions: obj.properties[0].value.split(',')
                }
            })
        })
        const anims = this.anims
        Object.keys(this.personInfo).forEach((key: string) => {
            const info = this.personInfo[key]
            const left_walk_name = info.chatRole.playerName + '-left-walk'
            const right_walk_name = info.chatRole.playerName + '-right-walk'
            const down_walk_name = info.chatRole.playerName + '-down-walk'
            const up_walk_name = info.chatRole.playerName + '-up-walk'
            const path = info.paths[getRandom(info.paths.length)]
            const direction = path.directions[getRandom(path.directions.length)]
            info.direction = direction

            anims.create({
                key: left_walk_name,
                frames: anims.generateFrameNames(info.chatRole.playerName, {
                    prefix: 'left-walk.',
                    start: 0,
                    end: 3,
                    zeroPad: 3
                }),
                frameRate: 6,
                repeat: -1
            })

            anims.create({
                key: right_walk_name,
                frames: anims.generateFrameNames(info.chatRole.playerName, {
                    prefix: 'right-walk.',
                    start: 0,
                    end: 3,
                    zeroPad: 3
                }),
                frameRate: 6,
                repeat: -1
            })

            anims.create({
                key: down_walk_name,
                frames: anims.generateFrameNames(info.chatRole.playerName, {
                    prefix: 'down-walk.',
                    start: 0,
                    end: 3,
                    zeroPad: 3
                }),
                frameRate: 6,
                repeat: -1
            })

            anims.create({
                key: up_walk_name,
                frames: anims.generateFrameNames(info.chatRole.playerName, {
                    prefix: 'up-walk.',
                    start: 0,
                    end: 3,
                    zeroPad: 3
                }),
                frameRate: 6,
                repeat: -1
            })
            info['sprite'] = this.add.sprite(path.postion.x, path.postion.y, info.chatRole.playerName)
            // .setScale(0.7)

            switch (direction) {
                case 'l':
                    info['sprite'].play(left_walk_name, true)
                    break
                case 'r':
                    info['sprite'].play(right_walk_name, true)
                    break
                case 'u':
                    info['sprite'].play(up_walk_name, true)
                    break
                case 'd':
                    info['sprite'].play(down_walk_name, true)
                    break
            }

            info.sprite.setInteractive()

            info.sprite.on('pointerdown', (e: any) => {
                info.wait = true
                info.sprite.stop()
                setTimeout(() => {
                    info.wait = false
                    info.sprite.play(info.sprite.anims.currentAnim.key)
                }, 1000)

                emitter.emit('chooseRole', info.chatRole)
            })
        })
    }
}
