#pragma once

#include "../../core/world/EdittableChunk.hpp"

namespace world::client {

class Chunk final: public EdittableChunk {
public:
    Chunk(std::istream &is): world::Chunk(is) { }
    /// Create from average
    Chunk(Voxel val): EdittableChunk(), isAverage(true), isMajorant(val.swap()) { voxels.fill(Voxel(val.material(), val.density())); }
    Chunk(): world::Chunk(), EdittableChunk() { }

    std::optional<Faces> update(float deltaTime, bool animate) override {
        for (auto it = futureEdits.begin(); it != futureEdits.end();) {
            it->second.second -= deltaTime;
            if (it->second.second <= 0 && animate) {
                invalidate(it->first);
                edits.emplace(it->first, it->second.first);
                it = futureEdits.erase(it);
            } else {
                ++it;
            }
        }
        return EdittableChunk::update(deltaTime, animate);
    }

    constexpr bool isTrusted(bool allowMajorant) const { return !isAverage || (allowMajorant && isMajorant); }
    void unsetMajorant() {
        assert(isMajorant);
        isMajorant = false;
    }

    /// Add future edit
    void addFutureEdit(Chunk::Edit edit, float delay) { futureEdits.insert_or_assign(edit.idx, std::make_pair(EditBody(edit), delay)); }

protected:
    /// Is temporary average
    const bool isAverage = false;
    /// Is temporary full valued
    bool isMajorant = false;

    /// Temporary animated changes
    robin_hood::unordered_map<chunk_voxel_idx, std::pair<Chunk::EditBody, float>> futureEdits;
};

/// Chunk full of air
static const std::shared_ptr<const Chunk> EMPTY_CHUNK = std::make_shared<Chunk>();

}