#include "game/scenes/surface_handle.hpp"

namespace Scenes {

    SurfaceHandle::SurfaceHandle(const char* file)
        : surface_(Jd8::loadSurface(file)) {}

    SurfaceHandle::~SurfaceHandle() {
        if (surface_ != nullptr) {
            Jd8::freeSurface(surface_);
        }
    }

    SurfaceHandle::SurfaceHandle(SurfaceHandle&& other) noexcept
        : surface_(other.surface_) {
        other.surface_ = nullptr;
    }

    auto SurfaceHandle::operator=(SurfaceHandle&& other) noexcept -> SurfaceHandle& {
        if (this != &other) {
            if (surface_ != nullptr) {
                Jd8::freeSurface(surface_);
            }
            surface_ = other.surface_;
            other.surface_ = nullptr;
        }
        return *this;
    }

    void SurfaceHandle::reset(const char* file) {
        if (surface_ != nullptr) {
            Jd8::freeSurface(surface_);
        }
        surface_ = (file != nullptr) ? Jd8::loadSurface(file) : nullptr;
    }

    void SurfaceHandle::adopt(Jd8::Surface raw) {
        if (surface_ != nullptr) {
            Jd8::freeSurface(surface_);
        }
        surface_ = raw;
    }

    auto SurfaceHandle::release() -> Jd8::Surface {
        Jd8::Surface r = surface_;
        surface_ = nullptr;
        return r;
    }

}  // namespace Scenes
