module demos.snake;

import app;

import bindbc.sdl;

import cimgui.cimgui;

import ecs.attributes;
import ecs.core;
import ecs.entity;
import ecs.manager;
import ecs.std;
import ecs.vector;

import ecs_utils.gfx.texture;
import ecs_utils.math.vector;
import ecs_utils.utils;

extern(C):

struct MapElement
{
    enum Type
    {
        empty = 0,
        snake = 1,
        apple = 2,
        wall = 3    
    }
    Type type;
    EntityID id;
}

struct Snake
{
    __gshared const (char)* tips = "Use \"WASD\" keys to move.";

    EntityTemplate* apple_tmpl;
    EntityTemplate* snake_tmpl;
    Texture snake_texture;
    Texture wall_texture;
    Texture apple_texture;

    bool move_system = true;
    bool draw_system = true;

    const int map_size = 18;

    MapElement[map_size * map_size] map;

    MapElement element(ivec2 pos)
    {
        uint index = pos.x + pos.y * map_size;
        if(index >= map.length)index = map.length - 1;
        return map[index];
    }

    void element(MapElement el, ivec2 pos)
    {
        uint index = pos.x + pos.y * map_size;
        if(index >= map.length)index = map.length - 1;
        map[index] = el;
    }

    void addApple()
    {
        ivec2 random_pos = ivec2(rand()%map_size,rand()%map_size);
        ivec2 base_pos = random_pos;
        while(element(random_pos).type != MapElement.Type.empty)
        {
            random_pos.x += 1;
            if(random_pos.x > map_size)
            {
                random_pos.x = 0;
                random_pos.y += 1;
                if(random_pos.y > map_size)random_pos.y = 0;
            }
            if(base_pos.x == random_pos.x && base_pos.y == random_pos.y)return;
        }
        CILocation* location = apple_tmpl.getComponent!CILocation;
        *location = random_pos;
        Entity* apple = launcher.manager.addEntity(apple_tmpl);
    }

    void drawMap()
    {
        foreach(x; 0 .. map_size)
        {
            foreach(y; 0 .. map_size)
            {
                switch(element(ivec2(x,y)).type)
                {
                    case MapElement.Type.apple:launcher.renderer.draw(apple_texture, vec2(x*32,y*32), vec2(32,32), vec4(0,0,1,1), 0, 0 , 0);break;
                    case MapElement.Type.snake:launcher.renderer.draw(snake_texture, vec2(x*32,y*32), vec2(32,32), vec4(0,0,1,1), 0, 0 , 0);break;
                    case MapElement.Type.wall:launcher.renderer.draw(wall_texture, vec2(x*32,y*32), vec2(32,32), vec4(0,0,1,1), 0, 0 , 0);break;
                    default:break;
                }
            }
        }
    }

}

struct CILocation
{
    mixin ECS.Component;

    alias location this;

    ivec2 location;
}

struct CLocation
{
    mixin ECS.Component;

    alias location this;

    vec2 location;
}

struct CSnake
{
    void onCreate()
    {
        parts.array = Mallocator.makeArray!ivec2(100);
    }

    void onDestroy()
    {
        Mallocator.dispose(parts.array);
    }

    mixin ECS.Component;

    struct Parts
    {
        uint length = 0;
        ivec2[] array;

        ivec2 opIndex(size_t ind) const
        {
            return array[ind];
        }

        ivec2[] opSlice() 
        {
            return array[0 .. length];
        }

        void opIndexAssign(ivec2 vec, size_t ind) 
        {
            array[ind] = vec;
        }

        size_t opDollar() const 
        {
            return length;
        }

        void add(ivec2 v)
        {
            length++;
            array[length-1] = v;
        }
    }

    Parts parts;
}

struct CApple
{
    mixin ECS.Component;
}

struct CParticle
{
    mixin ECS.Component;
}

struct CParticleVector
{
    mixin ECS.Component;

    vec2 velocity;
}

struct CMovement
{
    mixin ECS.Component;

    enum Direction : byte
    {
        up,
        down,
        left,
        right
    }   

    Direction direction;
}

struct CInput
{
    mixin ECS.Component;
}

struct AppleSystem
{
    mixin ECS.System!1;

    struct EntitiesData
    {
        uint length;
        @readonly Entity[] entities;
        @readonly CApple[] movement;
        @readonly CILocation[] location;
    }

    void onAddEntity(EntitiesData data)
    {
        foreach(i;0..data.length)
        {
            snake.element(MapElement(MapElement.Type.apple,data.entities[i].id),data.location[i]);
        }
    }
}

struct MoveSystem
{
    mixin ECS.System!64;

    struct EntitiesData
    {
        uint length;
        @readonly Entity[] entities;
        @readonly CMovement[] movement;
        @optional CSnake[] snakes;
        CILocation[] location;
    }

    void moveLocation(ref CILocation location, CMovement.Direction direction)
    {
        final switch(direction)
        {
            case CMovement.Direction.down:
                location.y -= 1;
                if(location.y < 0)location.y = snake.map_size - 1;
                break;
            case CMovement.Direction.up:
                location.y += 1;
                if(location.y >= snake.map_size)location.y = 0;
                break;
            case CMovement.Direction.left:
                location.x -= 1;
                if(location.x < 0)location.x = snake.map_size - 1;
                break;
            case CMovement.Direction.right:
                location.x += 1;
                if(location.x >= snake.map_size)location.x = 0;
                break;
        }
    }

    void moveSnake(ref CSnake snake, ivec2 location)
    {
        if(snake.parts.length)
        {
            .snake.element(MapElement(),snake.parts[0]);
            foreach(j; 0 .. snake.parts.length - 1)
            {
                snake.parts[j] = snake.parts[j + 1];
            }
            snake.parts[$-1] = location;
        }
        else .snake.element(MapElement(),location);
    }

    void onUpdate(EntitiesData data)
    {
        if(data.snakes)
        {
            foreach(i; 0..data.length)
            {
                ivec2 new_location = data.location[i];
                moveLocation(data.location[i], data.movement[i].direction);
                final switch(snake.element(data.location[i].location).type)
                {
                    case MapElement.Type.snake:
                        launcher.manager.removeEntity(data.entities[i].id);
                        break;
                    case MapElement.Type.wall:
                        launcher.manager.removeEntity(data.entities[i].id);
                        break;
                    case MapElement.Type.empty:
                        moveSnake(data.snakes[i], new_location);
                        snake.element(MapElement(MapElement.Type.snake, data.entities[i].id),data.location[i].location);
                        break;
                    case MapElement.Type.apple:
                        launcher.manager.removeEntity(snake.element(data.location[i].location).id);
                        data.snakes[i].parts.add(new_location);
                        snake.element(MapElement(MapElement.Type.snake, data.entities[i].id),new_location);
                        snake.element(MapElement(MapElement.Type.snake, data.entities[i].id),data.location[i].location);
                        snake.addApple();
                        break;
                }
            }
        }
        else
        {
            foreach(i; 0..data.length)
            {
                final switch(data.movement[i].direction)
                {
                    case CMovement.Direction.down:data.location[i].location.y -= 1;break;
                    case CMovement.Direction.up:data.location[i].location.y += 1;break;
                    case CMovement.Direction.left:data.location[i].location.x -= 1;break;
                    case CMovement.Direction.right:data.location[i].location.x += 1;break;
                }
            }
        }
        
    }
}

struct InputSystem
{
    mixin ECS.System!64;

    struct EntitiesData
    {
        uint length;
        CMovement[] movement;
        @readonly CInput[] input;
    }

    void onUpdate(EntitiesData data)
    {
        foreach(i; 0..data.length)
        {
            if(launcher.getKeyState(SDL_SCANCODE_W))
            {
                data.movement[i].direction = CMovement.Direction.up;
            }
            else if(launcher.getKeyState(SDL_SCANCODE_S))
            {
                data.movement[i].direction = CMovement.Direction.down;
            }
            else if(launcher.getKeyState(SDL_SCANCODE_A))
            {
                data.movement[i].direction = CMovement.Direction.left;
            }
            else if(launcher.getKeyState(SDL_SCANCODE_D))
            {
                data.movement[i].direction = CMovement.Direction.right;
            }
        }
    }
}

struct FixSnakeDirectionSystem
{
    mixin ECS.System!64;

    struct EntitiesData
    {
        uint length;
        CMovement[] movement;
        @readonly CILocation[] location;
        const (CSnake)[] snake;
    }

    void onUpdate(EntitiesData data)
    {
        foreach(i; 0..data.length)
        {
            ivec2 last_location;
            if(data.snake[i].parts.length)last_location = data.snake[i].parts[$ - 1];
            else continue;
            ivec2 next_location = data.location[i];
            
            final switch(data.movement[i].direction)
            {
                case CMovement.Direction.up:
                    next_location.y += 1;
                    if(next_location.y >= snake.map_size)next_location.y = 0;
                    if(next_location.x == last_location.x && next_location.y == last_location.y)
                    {
                        data.movement[i].direction = CMovement.Direction.down;
                    }
                    break;
                case CMovement.Direction.down:
                    next_location.y -= 1;
                    if(next_location.y < 0)next_location.y = snake.map_size - 1;
                    if(next_location.x == last_location.x && next_location.y == last_location.y)
                    {
                        data.movement[i].direction = CMovement.Direction.up;
                    }
                    break;
                case CMovement.Direction.left:
                    next_location.x -= 1;
                    if(next_location.x < 0)next_location.x = snake.map_size - 1;
                    if(next_location.x == last_location.x && next_location.y == last_location.y)
                    {
                        data.movement[i].direction = CMovement.Direction.right;
                    }
                    break;
                case CMovement.Direction.right:
                    next_location.x += 1;
                    if(next_location.x >= snake.map_size)next_location.x = 0;
                    if(next_location.x == last_location.x && next_location.y == last_location.y)
                    {
                        data.movement[i].direction = CMovement.Direction.left;
                    }
                    break;
            }
        }
    }
}

struct CleanSystem
{
    mixin ECS.System!64;

    struct EntitiesData
    {
        uint length;
        Entity[] entities;
    }

    void onUpdate(EntitiesData data)
    {
        foreach(i; 0..data.length)
        {
            launcher.manager.removeEntity(data.entities[i].id);
        }
    }
}

__gshared Snake* snake;

void snakeStart()
{
    snake = Mallocator.make!Snake;

    snake.snake_texture.create();
    snake.snake_texture.load("assets/textures/buckler.png");

    snake.apple_texture.create();
    snake.apple_texture.load("assets/textures/buckler.png");

    snake.wall_texture.create();
    snake.wall_texture.load("assets/textures/buckler.png");

    launcher.manager.beginRegister();

    launcher.manager.registerPass("fixed");

    launcher.manager.registerComponent!CLocation;
    launcher.manager.registerComponent!CILocation;
    launcher.manager.registerComponent!CSnake;
    launcher.manager.registerComponent!CApple;
    launcher.manager.registerComponent!CParticle;
    launcher.manager.registerComponent!CMovement;
    launcher.manager.registerComponent!CInput;

    launcher.manager.registerSystem!MoveSystem(0,"fixed");
    launcher.manager.registerSystem!InputSystem(-100);
    launcher.manager.registerSystem!FixSnakeDirectionSystem(-1,"fixed");
    launcher.manager.registerSystem!AppleSystem(-1,"fixed");

    launcher.manager.endRegister();

    launcher.gui_manager.addSystem(MoveSystem.system_id,"Move System");
    launcher.gui_manager.addSystem(InputSystem.system_id,"Input System");
    launcher.gui_manager.addSystem(FixSnakeDirectionSystem.system_id,"Fix Direction System");

    {
        ushort[4] components = [CILocation.component_id, CSnake.component_id, CMovement.component_id, CInput.component_id];
        snake.snake_tmpl = launcher.manager.allocateTemplate(components);
        CILocation* loc_comp = snake.snake_tmpl.getComponent!CILocation;
        loc_comp.location = ivec2(2,2);
        launcher.manager.addEntity(snake.snake_tmpl);
    }

    {
        ushort[2] components = [CILocation.component_id, CApple.component_id];
        snake.apple_tmpl = launcher.manager.allocateTemplate(components);
        snake.addApple();
    }

    launcher.gui_manager.addTemplate(snake.snake_tmpl, "Snake");
    launcher.gui_manager.addTemplate(snake.apple_tmpl, "Apple");

    /*foreach(i; 0..10)
        foreach(j; 0..10)
        {
            loc_comp.location = vec2(i*32+64,j*32+64);
            launcher.manager.addEntity(simple.tmpl);
        }*/
}

void snakeEnd()
{
    snake.wall_texture.destroy();
    snake.apple_texture.destroy();
    snake.snake_texture.destroy();

    //launcher.manager.freeTemplate(simple.tmpl);
    Mallocator.dispose(snake);
}

void snakeTool(vec2 position, Tool tool, int size)
{
    switch(tool)
    {
        case Tool.entity_spawner:
            {
                EntityTemplate* tmpl = launcher.gui_manager.getSelectedTemplate();
                CLocation* location = tmpl.getComponent!CLocation;
                if(location)
                {
                    position.x += (randomf - 0.5) * size;
                    position.y += (randomf - 0.5) * size;
                    *location = position;
                }
                CILocation* ilocation = tmpl.getComponent!CILocation;
                if(ilocation)
                {
                    position.x += (randomf - 0.5) * size;
                    position.y += (randomf - 0.5) * size;
                    ivec2 ipos;
                    ipos.x = cast(int)(position.x / 32);
                    ipos.y = cast(int)(position.y / 32);
                    *ilocation = ipos;
                    if(snake.element(ipos).type != MapElement.Type.empty)return;
                }
                launcher.manager.addEntity(tmpl);
            }
            break;
        default:
            break;
    }
}

void snakeEvent(SDL_Event* event)
{

}

bool snakeLoop()
{
    /*if(launcher.show_demo_wnd)
    {
        igSetNextWindowPos(ImVec2(800 - 260, 30), ImGuiCond_Once, ImVec2(0,0));
        igSetNextWindowSize(ImVec2(250, 0), ImGuiCond_Once);
        if(igBegin("Snake",&launcher.show_demo_wnd,0))
        {
            
        }
        igEnd();
    }*/

    launcher.manager.begin();

    float delta_time = launcher.delta_time;
    if(delta_time > 2000)delta_time = 2000;
    __gshared float time = 0;

    if(launcher.getKeyState(SDL_SCANCODE_SPACE))time += delta_time * 3;
    else time += delta_time;
    
    while(time > 100)
    {
        time -= 100;
        
        launcher.manager.update("fixed");
    }

    launcher.manager.update();

    launcher.manager.end();

    snake.drawMap();

    return true;
}