#include "Chunk.h"

#include <Shader.h>

#include "ChunkFluidModel.h"
#include "ChunkGroundModel.h"
#include "Constants.h"
#include "CustomDX11API.h"
#include "FactoryCraftModel.h"
#include "Globals.h"
#include "Registries.h"
#include "TransparentChunkGroundModel.h"

Chunk::Chunk(Framework::Punkt location)
    : ReferenceCounter(),
      location(location),
      isLoading(0),
      lightChanged(0)
{
    blocks = new Block*[CHUNK_SIZE * CHUNK_SIZE * WORLD_HEIGHT];
    memset(blocks, 0, CHUNK_SIZE * CHUNK_SIZE * WORLD_HEIGHT * sizeof(Block*));
    FactoryCraftModel* ground = new FactoryCraftModel();
    Model3DData* chunkModel
        = uiFactory.initParam.bildschirm->zGraphicsApi()->getModel(
            Text("chunk_ground_") + location.x + location.y);
    if (!chunkModel)
    {
        chunkModel
            = uiFactory.initParam.bildschirm->zGraphicsApi()->createModel(
                Text("chunk_ground_") + location.x + location.y);
    }
    chunkModel->setAmbientFactor(0.f);
    chunkModel->setDiffusFactor(1.f);
    chunkModel->setSpecularFactor(0.f);
    chunkModel->setVertecies(0, 0);
    ground->setModelDaten(chunkModel);
    ground->setPosition(
        (float)location.x, (float)location.y, (float)WORLD_HEIGHT / 2.f);
    ground->tick(0);
    groundModel = new ChunkGroundModel(ground, this);
    FactoryCraftModel* transparentGround = new FactoryCraftModel();
    chunkModel
        = uiFactory.initParam.bildschirm->zGraphicsApi()->getModel(
            Text("transparent_chunk_ground_") + location.x + location.y);
    if (!chunkModel)
    {
        chunkModel
            = uiFactory.initParam.bildschirm->zGraphicsApi()->createModel(
                Text("transparent_chunk_ground_") + location.x + location.y);
    }
    chunkModel->setAmbientFactor(0.f);
    chunkModel->setDiffusFactor(1.f);
    chunkModel->setSpecularFactor(0.f);
    chunkModel->setVertecies(0, 0);
    transparentGround->setModelDaten(chunkModel);
    transparentGround->setPosition(
        (float)location.x, (float)location.y, (float)WORLD_HEIGHT / 2.f);
    transparentGround->tick(0);
    transparentGroundModel
        = new TransparentChunkGroundModel(transparentGround, this);
    FactoryCraftModel* fluids = new FactoryCraftModel();
    chunkModel = uiFactory.initParam.bildschirm->zGraphicsApi()->getModel(
        Text("chunk_fluids_") + location.x + location.y);
    if (!chunkModel)
    {
        chunkModel
            = uiFactory.initParam.bildschirm->zGraphicsApi()->createModel(
                Text("chunk_fluids_") + location.x + location.y);
    }
    chunkModel->setAmbientFactor(0.f);
    chunkModel->setDiffusFactor(1.f);
    chunkModel->setSpecularFactor(0.f);
    chunkModel->setVertecies(0, 0);
    fluids->setModelDaten(chunkModel);
    fluids->setPosition(
        (float)location.x, (float)location.y, (float)WORLD_HEIGHT / 2.f);
    fluids->tick(0);
    fluidModel = new ChunkFluidModel(fluids, this);
}

Chunk::Chunk(Framework::Punkt location, Framework::StreamReader* zReader)
    : Chunk(location)
{
    load(zReader);
    buildModel(groundModel);
    buildModel(transparentGroundModel);
    buildModel(fluidModel);
}

Chunk::~Chunk()
{
    char msg = 1; // remove observer
    if (World::INSTANCE)
    {
        World::INSTANCE->zClient()->chunkAPIRequest(location, &msg, 1);
    }
    for (int i = 0; i < CHUNK_SIZE * CHUNK_SIZE * WORLD_HEIGHT; i++)
    {
        if (blocks[i])
        {
            blocks[i]->release();
            blocks[i] = 0;
        }
    }
    delete[] blocks;
    groundModel->release();
    transparentGroundModel->release();
    fluidModel->release();
}

void Chunk::appendAnimation(
    Block* zB, int boneId, double time, Vec3<float> pos, Vec3<float> rot)
{
    if (!zB->zSkeleton() || !zB->zSkeleton()->zBone(boneId)) return;
    acs.lock();
    for (BlockAnimation* animation : animations)
    {
        if (animation->zBlock() == zB)
        {
            animation->appendAnimation(boneId, time, pos, rot);
            acs.unlock();
            return;
        }
    }
    SkeletonAnimation* sa = new SkeletonAnimation();
    Bone* bone = zB->zSkeleton()->zBone(boneId);
    sa->addAnimation(boneId, bone->getPosition(), bone->getRotation());
    sa->addKeyFrame(boneId, time, pos, rot);
    animations.add(new BlockAnimation(dynamic_cast<Block*>(zB->getThis()), sa));
    acs.unlock();
}

void Chunk::load(Framework::StreamReader* zReader)
{
    cs.lock();
    for (int i = 0; i < CHUNK_SIZE * CHUNK_SIZE * WORLD_HEIGHT; i++)
    {
        if (blocks[i])
        {
            blocks[i]->release();
            blocks[i] = 0;
        }
    }
    cs.unlock();
    isLoading = 1;
    Framework::Vec3<int> pos = {0, 0, 0};
    unsigned short id;
    zReader->lese((char*)&id, 2);
    int count = 0;
    while (id)
    {
        int index;
        zReader->lese((char*)&index, 4);
        short fill = 0;
        if (blockTypes[id]->isFluid())
        {
            zReader->lese((char*)&fill, 2);
        }
        pos = Vec3<int>((index / WORLD_HEIGHT) / CHUNK_SIZE,
            (index / WORLD_HEIGHT) % CHUNK_SIZE,
            index % WORLD_HEIGHT);
        if (blockTypes[id]->doesNeedInstance())
        {
            cs.lock();
            Block* b = blockTypes[id]->createBlock(
                {pos.x + location.x - CHUNK_SIZE / 2,
                    pos.y + location.y - CHUNK_SIZE / 2,
                    pos.z});
            b->setFill(fill);
            blocks[index] = b;
            cs.unlock();
            vcs.lock();
            if (b->isVisible())
            {
                if (!blockTypes[id]->getModelInfo().getModelName().istGleich(
                        "cube")
                    && !blockTypes[id]->getModelInfo().getModelName().istGleich(
                        "grass"))
                {
                    b->tick(0);
                    visibleBlocks.add(b);
                }
            }
            count++;
            vcs.unlock();
        }
        zReader->lese((char*)&id, 2);
    }
    std::cout << "Loaded " << count << " blocks\n";
    int index = 0;
    // light
    zReader->lese((char*)&index, 4);
    char lightData[6];
    while (index >= -1)
    {
        if (index == -1)
        {
            int x = 0;
            int y = 0;
            int z = 0;
            zReader->lese((char*)&x, 4);
            zReader->lese((char*)&y, 4);
            zReader->lese((char*)&z, 4);
            zReader->lese(lightData, 6);
            if (x == -1)
            {
                int cacheIndex = y * WORLD_HEIGHT + z;
                Block* zB = blocks[cacheIndex];
                if (zB)
                {
                    zB->setLightData(WEST, (unsigned char*)lightData);
                }
            }
            else if (y == -1)
            {
                int cacheIndex = (x * CHUNK_SIZE) * WORLD_HEIGHT + z;
                Block* zB = blocks[cacheIndex];
                if (zB)
                {
                    zB->setLightData(NORTH, (unsigned char*)lightData);
                }
            }
            else if (x == CHUNK_SIZE)
            {
                int cacheIndex
                    = ((CHUNK_SIZE - 1) * CHUNK_SIZE + y) * WORLD_HEIGHT + z;
                Block* zB = blocks[cacheIndex];
                if (zB)
                {
                    zB->setLightData(EAST, (unsigned char*)lightData);
                }
            }
            else if (y == CHUNK_SIZE)
            {
                int cacheIndex
                    = (x * CHUNK_SIZE + (CHUNK_SIZE - 1)) * WORLD_HEIGHT + z;
                Block* zB = blocks[cacheIndex];
                if (zB)
                {
                    zB->setLightData(SOUTH, (unsigned char*)lightData);
                }
            }
        }
        else
        {
            zReader->lese(lightData, 6);
            Framework::Vec3<int> location((index / WORLD_HEIGHT) / CHUNK_SIZE,
                (index / WORLD_HEIGHT) % CHUNK_SIZE,
                index % WORLD_HEIGHT);
            for (int i = 0; i < 6; i++)
            {
                Framework::Vec3<int> pos
                    = location + getDirection(getDirectionFromIndex(i));
                if (pos.z >= 0 && pos.z < WORLD_HEIGHT)
                {
                    if (pos.x >= 0 && pos.x < CHUNK_SIZE && pos.y >= 0
                        && pos.y < CHUNK_SIZE)
                    {
                        int cacheIndex
                            = (pos.x * CHUNK_SIZE + pos.y) * WORLD_HEIGHT
                            + pos.z;
                        Block* zB = blocks[cacheIndex];
                        if (zB)
                        {
                            bool visible = zB->isVisible();
                            zB->setLightData(
                                getOppositeDirection(getDirectionFromIndex(i)),
                                (unsigned char*)lightData);
                            if (zB->isVisible() && !visible)
                            {
                                vcs.lock();
                                zB->tick(0);
                                visibleBlocks.add(zB);
                                vcs.unlock();
                            }
                        }
                    }
                    else
                    {
                        pos.x += this->location.x - CHUNK_SIZE / 2;
                        pos.y += this->location.y - CHUNK_SIZE / 2;
                        Block* zB = World::INSTANCE->zBlockAt(pos);
                        if (zB)
                        {
                            bool visible = zB->isVisible();
                            zB->setLightData(
                                getOppositeDirection(getDirectionFromIndex(i)),
                                (unsigned char*)lightData);
                            if (zB->isVisible() && !visible)
                            {
                                Chunk* c = World::INSTANCE->zChunk(
                                    World::INSTANCE->getChunkCenter(
                                        pos.x, pos.y));
                                c->vcs.lock();
                                zB->tick(0);
                                c->visibleBlocks.add(zB);
                                c->vcs.unlock();
                            }
                        }
                    }
                }
            }
        }
        zReader->lese((char*)&index, 4);
    }
    isLoading = 0;
}

void Chunk::buildModel(ChunkModelBuilder* builder)
{
    vcs.lock();
    modelChanged &= ~builder->getType();
    lightChanged &= ~builder->getType();
    builder->buildModel();
    vcs.unlock();
}

void Chunk::updateLight(ChunkModelBuilder* builder)
{
    vcs.lock();
    lightChanged &= ~builder->getType();
    builder->updateLightning();
    vcs.unlock();
}

void Chunk::renderSolid(std::function<void(Model3D*)> f)
{
    vcs.lock();
    CustomDX11API* api
        = (CustomDX11API*)uiFactory.initParam.bildschirm->zGraphicsApi();
    api->setCullBack(false);
    f(groundModel->zModel());
    api->setCullBack(true);
    float dist = 0.f;
    if (api->isInFrustrum(groundModel->zModel()->getPos(),
            (CHUNK_SIZE / 2.f, CHUNK_SIZE / 2.f, WORLD_HEIGHT / 2.f),
            &dist))
    {
        for (Block* b : visibleBlocks)
        {
            f(b);
        }
    }
    vcs.unlock();
}

void Chunk::renderTransparent(std::function<void(Model3D*)> f)
{
    CustomDX11API* api
        = (CustomDX11API*)uiFactory.initParam.bildschirm->zGraphicsApi();
    api->setCullBack(false);
    f(transparentGroundModel->zModel());
    f(fluidModel->zModel());
    api->setCullBack(true);
}

bool Chunk::tick(std::function<void(Model3D*)> f, double time)
{
    acs.lock();
    vcs.lock(); // TODO: enshure no dead lock occures
    if ((modelChanged | CombinedModels::GROUND) == modelChanged)
        buildModel(groundModel);
    if ((modelChanged | CombinedModels::TRANSPARENT_GROUND) == modelChanged)
        buildModel(transparentGroundModel);
    if ((modelChanged | CombinedModels::FLUID) == modelChanged)
        buildModel(fluidModel);
    if ((lightChanged | CombinedModels::GROUND) == lightChanged)
        updateLight(groundModel);
    if ((lightChanged | CombinedModels::TRANSPARENT_GROUND) == lightChanged)
        updateLight(transparentGroundModel);
    if ((lightChanged | CombinedModels::FLUID) == lightChanged)
        updateLight(fluidModel);
    bool res = groundModel->zModel()->tick(time);
    res |= transparentGroundModel->zModel()->tick(time);
    res |= fluidModel->zModel()->tick(time);
    auto iterator = animations.begin();
    while (iterator)
    {
        if (iterator->tick(time))
        {
            res |= iterator->zBlock()->tick(time);
            if (iterator->isFinished())
            {
                iterator.remove();
                continue;
            }
        }
        else
        {
            iterator.remove();
            continue;
        }
        ++iterator;
    }
    vcs.unlock();
    acs.unlock();
    return 1;
}

void Chunk::destroy()
{
    Model3DData* chunkModel = groundModel->zModel()->zModelData();
    // remove old model
    while (chunkModel->getPolygonAnzahl() > 0)
    {
        chunkModel->removePolygon(0);
    }
    chunkModel->setVertecies(0, 0);
    chunkModel = transparentGroundModel->zModel()->zModelData();
    // remove old model
    while (chunkModel->getPolygonAnzahl() > 0)
    {
        chunkModel->removePolygon(0);
    }
    chunkModel->setVertecies(0, 0);
    chunkModel = fluidModel->zModel()->zModelData();
    // remove old model
    while (chunkModel->getPolygonAnzahl() > 0)
    {
        chunkModel->removePolygon(0);
    }
    chunkModel->setVertecies(0, 0);
}

void Chunk::api(char* message)
{
    switch (message[0])
    {
    case 0: // set block
        {
            int index = *(int*)(message + 1);
            int id = *(int*)(message + 5);
            Framework::Vec3<int> location((index / WORLD_HEIGHT) / CHUNK_SIZE,
                (index / WORLD_HEIGHT) % CHUNK_SIZE,
                index % WORLD_HEIGHT);
            location.x += this->location.x - CHUNK_SIZE / 2;
            location.y += this->location.y - CHUNK_SIZE / 2;
            if (blockTypes[id]->doesNeedInstance())
            {
                Block* zB = blockTypes[id]->createBlock(location);
                setBlock(zB);
            }
            else
            {
                Block* zB = zBlockAt(location);
                if (zB) removeBlock(zB);
            }
            break;
        }
    case 1: // animate block
        {
            int index = *(int*)(message + 1);
            int boneId = *(int*)(message + 5);
            double time = *(double*)(message + 9);
            Framework::Vec3<float> pos;
            pos.x = *(float*)(message + 17);
            pos.y = *(float*)(message + 21);
            pos.z = *(float*)(message + 25);
            Framework::Vec3<float> rot;
            rot.x = *(float*)(message + 29);
            rot.y = *(float*)(message + 33);
            rot.z = *(float*)(message + 37);
            Framework::Vec3<int> location((index / WORLD_HEIGHT) / CHUNK_SIZE,
                (index / WORLD_HEIGHT) % CHUNK_SIZE,
                index % WORLD_HEIGHT);
            location.x += this->location.x - CHUNK_SIZE / 2;
            location.y += this->location.y - CHUNK_SIZE / 2;
            Block* zB = zBlockAt(location);
            if (zB) appendAnimation(zB, boneId, time, pos, rot);
            break;
        }
    }
}

Block* Chunk::zBlockAt(Framework::Vec3<int> location)
{
    location.x = location.x % CHUNK_SIZE;
    location.y = location.y % CHUNK_SIZE;
    if (location.x < 0) location.x += CHUNK_SIZE;
    if (location.y < 0) location.y += CHUNK_SIZE;
    int index
        = (location.x * CHUNK_SIZE + location.y) * WORLD_HEIGHT + location.z;
    return blocks[index];
}

void Chunk::setBlock(Block* block)
{
    cs.lock();
    Framework::Vec3<int> pos = block->getLocation();
    pos.x = pos.x % CHUNK_SIZE;
    pos.y = pos.y % CHUNK_SIZE;
    if (pos.x < 0) pos.x += CHUNK_SIZE;
    if (pos.y < 0) pos.y += CHUNK_SIZE;
    int index = (pos.x * CHUNK_SIZE + pos.y) * WORLD_HEIGHT + pos.z;
    bool newAffectsGround
        = block
       && (block->zBlockType()->getModelInfo().getModelName().istGleich("cube")
           || block->zBlockType()->getModelInfo().getModelName().istGleich(
               "grass"));
    bool affectsGround
        = blocks[index]
       && (blocks[index]->zBlockType()->getModelInfo().getModelName().istGleich(
               "cube")
           || blocks[index]
                  ->zBlockType()
                  ->getModelInfo()
                  .getModelName()
                  .istGleich("grass"));
    if (blocks[index])
    {
        vcs.lock();
        for (Framework::Iterator<Block*> vi = visibleBlocks.begin(); vi; vi++)
        {
            if (blocks[index] == (Block*)vi)
            {
                vi.remove();
                break;
            }
        }
        vcs.unlock();
        blocks[index]->copyLightTo(block);
        blocks[index]->release();
        blocks[index] = block;
        cs.unlock();
        vcs.lock();
        if (affectsGround || newAffectsGround)
        {
            modelChanged = 1;
        }
        if (block && block->isVisible() && !newAffectsGround)
        {
            block->tick(0);
            visibleBlocks.add(block);
        }
        vcs.unlock();
        return;
    }
    blocks[index] = block;
    cs.unlock();
    vcs.lock();
    if (affectsGround || newAffectsGround)
    {
        modelChanged = 1;
    }
    if (block && block->isVisible() && !newAffectsGround)
    {
        block->tick(0);
        visibleBlocks.add(block);
    }
    vcs.unlock();
}

void Chunk::removeBlock(Block* zBlock)
{
    cs.lock();
    vcs.lock();
    for (Framework::Iterator<Block*> iterator = visibleBlocks.begin(); iterator;
         iterator++)
    {
        if (zBlock == (Block*)iterator)
        {
            iterator.remove();
            break;
        }
    }
    vcs.unlock();
    Vec3<int> pos = zBlock->getLocation();
    pos.x = pos.x % CHUNK_SIZE;
    pos.y = pos.y % CHUNK_SIZE;
    if (pos.x < 0) pos.x += CHUNK_SIZE;
    if (pos.y < 0) pos.y += CHUNK_SIZE;
    int index = (pos.x * CHUNK_SIZE + pos.y) * WORLD_HEIGHT + pos.z;
    if (blocks[index])
    {
        modelChanged |= blocks[index]->getPartOfModels();
        blocks[index]->release();
        blocks[index] = 0;
    }
    cs.unlock();
}

void Chunk::blockVisibilityChanged(Block* zB)
{
    vcs.lock();
    if (zB->isVisible())
    {
        zB->tick(0);
        visibleBlocks.add(zB);
    }
    else
    {
        for (Framework::Iterator<Block*> iterator = visibleBlocks.begin();
             iterator;
             iterator++)
        {
            if (zB == (Block*)iterator)
            {
                iterator.remove();
                break;
            }
        }
    }
    vcs.unlock();
}

Framework::Punkt Chunk::getCenter() const
{
    return location;
}

Framework::Vec3<int> Chunk::getMin() const
{
    return {location.x - CHUNK_SIZE / 2, location.y - CHUNK_SIZE / 2, 0};
}

Framework::Vec3<int> Chunk::getMax() const
{
    return {
        location.x + CHUNK_SIZE / 2, location.y + CHUNK_SIZE / 2, WORLD_HEIGHT};
}

void Chunk::setModelChanged(int type)
{
    modelChanged |= type;
}

void Chunk::setLightChanged(int type)
{
    lightChanged |= type;
}