#ifndef _NXSTL_THREAD
#define _NXSTL_THREAD 1
#ifdef __SWITCH__
extern "C" {
#include <switch/kernel/thread.h>
#include <switch/arm/tls.h>
#include <switch/result.h>
}
#include <memory>

namespace std _GLIBCXX_VISIBILITY(default)
{

/// thread
class thread
{
public:
    // Abstract base class for types that wrap arbitrary functors to be
    // invoked in the new thread of execution.
    struct _State
    {
        virtual ~_State() = default;
        virtual void _M_run() = 0;
    };
    using _State_ptr = unique_ptr<_State>;

    typedef Thread			native_handle_type;

    /// thread::id
    class id
    {
        native_handle_type	_M_thread;

    public:
        id() noexcept : _M_thread() { }

        explicit
        id(native_handle_type __id) : _M_thread(__id) { }

    private:
        friend class thread;
        friend class hash<thread::id>;

        friend bool
        operator==(thread::id __x, thread::id __y) noexcept;

        friend bool
        operator<(thread::id __x, thread::id __y) noexcept;

        template<class _CharT, class _Traits>
        friend basic_ostream<_CharT, _Traits>&
        operator<<(basic_ostream<_CharT, _Traits>& __out, thread::id __id);
    };

private:
    id				_M_id;

public:
    thread() noexcept = default;
    // _GLIBCXX_RESOLVE_LIB_DEFECTS
    // 2097.  packaged_task constructors should be constrained
    thread(thread&) = delete;
    thread(const thread&) = delete;
    thread(const thread&&) = delete;

    thread(thread&& __t) noexcept
    { swap(__t); }

    template<typename _Callable, typename... _Args>
    explicit
    thread(_Callable&& __f, _Args&&... __args)
    {
        _M_start_thread(_S_make_state(
            __make_invoker(std::forward<_Callable>(__f),
                           std::forward<_Args>(__args)...)));
    }

    ~thread()
    {
        if (joinable())
            std::terminate();
    }

    thread& operator=(const thread&) = delete;

    thread& operator=(thread&& __t) noexcept
    {
        if (joinable())
            std::terminate();
        swap(__t);
        return *this;
    }

    void
    swap(thread& __t) noexcept
    { std::swap(_M_id, __t._M_id); }

    bool
    joinable() const noexcept
    { return !(_M_id == id()); }

    void
    join()
    {
        threadWaitForExit(&_M_id._M_thread);
        _M_id = id();
    }

    void
    detach()
    {
        _M_id = id();
    }

    thread::id
    get_id() const noexcept
    { return _M_id; }

    /** @pre thread is joinable
     */
    native_handle_type
    native_handle()
    { return _M_id._M_thread; }

    // Returns a value that hints at the number of hardware thread contexts.
    static unsigned int
    hardware_concurrency() noexcept
    {
        return 3;
    }

private:
    template<typename _Callable>
    struct _State_impl : public _State
    {
        _Callable		_M_func;

        _State_impl(_Callable&& __f) : _M_func(std::forward<_Callable>(__f))
        { }

        void
        _M_run() { _M_func(); }
    };

    static void
    execute_native_thread_routine(void *arg)
    {
        reinterpret_cast<_State*>(arg)->_M_run();
    }

    void
    _M_start_thread(_State_ptr state)
    {
        Result res = threadCreate(&_M_id._M_thread, execute_native_thread_routine,
                                  state.get(), 8192, 0x2B, -2);
        if (R_FAILED(res))
            __throw_system_error(res);
        res = threadStart(&_M_id._M_thread);
        if (R_FAILED(res))
            __throw_system_error(res);
        state.release();
    }

    template<typename _Callable>
    static _State_ptr
    _S_make_state(_Callable&& __f)
    {
        using _Impl = _State_impl<_Callable>;
        return _State_ptr{new _Impl{std::forward<_Callable>(__f)}};
    }

private:
    // A call wrapper that does INVOKE(forwarded tuple elements...)
    template<typename _Tuple>
    struct _Invoker
    {
        _Tuple _M_t;

        template<size_t _Index>
        static __tuple_element_t<_Index, _Tuple>&&
        _S_declval();

        template<size_t... _Ind>
        auto
        _M_invoke(_Index_tuple<_Ind...>)
        noexcept(noexcept(std::__invoke(_S_declval<_Ind>()...)))
        -> decltype(std::__invoke(_S_declval<_Ind>()...))
        { return std::__invoke(std::get<_Ind>(std::move(_M_t))...); }

        using _Indices
        = typename _Build_index_tuple<tuple_size<_Tuple>::value>::__type;

        auto
        operator()()
        noexcept(noexcept(std::declval<_Invoker&>()._M_invoke(_Indices())))
        -> decltype(std::declval<_Invoker&>()._M_invoke(_Indices()))
        { return _M_invoke(_Indices()); }
    };

    template<typename... _Tp>
    using __decayed_tuple = tuple<typename std::decay<_Tp>::type...>;

public:
    // Returns a call wrapper that stores
    // tuple{DECAY_COPY(__callable), DECAY_COPY(__args)...}.
    template<typename _Callable, typename... _Args>
    static _Invoker<__decayed_tuple<_Callable, _Args...>>
    __make_invoker(_Callable&& __callable, _Args&&... __args)
    {
        return { __decayed_tuple<_Callable, _Args...>{
            std::forward<_Callable>(__callable), std::forward<_Args>(__args)...
        } };
    }
};

inline void
swap(thread& __x, thread& __y) noexcept
{ __x.swap(__y); }

inline bool
operator==(thread::id __x, thread::id __y) noexcept
{
    // pthread_equal is undefined if either thread ID is not valid, so we
    // can't safely use __gthread_equal on default-constructed values (nor
    // the non-zero value returned by this_thread::get_id() for
    // single-threaded programs using GNU libc). Assume EqualityComparable.
    return __x._M_thread.handle == __y._M_thread.handle;
}

inline bool
operator!=(thread::id __x, thread::id __y) noexcept
{ return !(__x == __y); }

inline bool
operator<(thread::id __x, thread::id __y) noexcept
{
    // Pthreads doesn't define any way to do this, so we just have to
    // assume native_handle_type is LessThanComparable.
    return __x._M_thread.handle < __y._M_thread.handle;
}

inline bool
operator<=(thread::id __x, thread::id __y) noexcept
{ return !(__y < __x); }

inline bool
operator>(thread::id __x, thread::id __y) noexcept
{ return __y < __x; }

inline bool
operator>=(thread::id __x, thread::id __y) noexcept
{ return !(__x < __y); }

// DR 889.
/// std::hash specialization for thread::id.
template<>
struct hash<thread::id>
    : public __hash_base<size_t, thread::id>
{
    size_t
    operator()(const thread::id& __id) const noexcept
    { return std::_Hash_impl::hash(__id._M_thread); }
};

template<class _CharT, class _Traits>
inline basic_ostream<_CharT, _Traits>&
operator<<(basic_ostream<_CharT, _Traits>& __out, thread::id __id)
{
    if (__id == thread::id())
        return __out << "thread::id of a non-executing thread";
    else
        return __out << __id._M_thread;
}

namespace this_thread
{
/// get_id
inline thread::id
get_id() noexcept
{
    Thread ret;
    uint8_t* tls = (uint8_t*)armGetTls();
    uint8_t* threadCtx = *(uint8_t**)(tls + 0x1F8);
    ret.handle = *(Handle*)(threadCtx + 0x1B8);
    ret.stack_mem = *(void**)(threadCtx + 0x48);
    ret.stack_mirror = *(void**)(threadCtx + 0x50);
    ret.stack_sz = *(size_t*)(threadCtx + 0x58);
    return thread::id(ret);
}
}

}

#endif
#endif