/*******************************************************************************
 * Copyright (c) 2014, Jan Koester jan.koester@gmx.net
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright
 *      notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 *      notice, this list of conditions and the following disclaimer in the
 *      documentation and/or other materials provided with the distribution.
 * Neither the name of the <organization> nor the
 *      names of its contributors may be used to endorse or promote products
 *      derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *******************************************************************************/

#include <thread>
#include <vector>
#include <memory>

#include "socket.h"
#include "connection.h"

#pragma once

namespace netplus {
        class EventWorker;
        class pollapi;

        // ===================================================
        // Cross-platform socket readiness waiting.
        // Abstracts epoll (Linux), kqueue (BSD), IOCP (Windows),
        // select/poll (fallback) behind a simple interface.
        // Each event backend (event/*.cpp) provides the implementation.
        // ===================================================
        class socketwait {
        public:
            socketwait();
            ~socketwait();

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

            // Wait until socket is readable.
            // timeout_ms: -1 = infinite, 0 = return immediately, >0 = milliseconds
            // Returns true if ready, false on timeout.
            bool waitRead(socket &sock, int timeout_ms = -1);

            // Wait until socket is writable.
            bool waitWrite(socket &sock, int timeout_ms = -1);

            // Wait until at least one of the given sockets is readable.
            // ready: output vector, resized to match sockets.size(), set to
            //        true for each socket that is readable.
            // Returns number of ready sockets (0 on timeout).
            int waitReadMulti(std::vector<socket*> &sockets,
                              std::vector<bool> &ready,
                              int timeout_ms = -1);

            // Check if the peer has disconnected (non-blocking).
            bool isDisconnected(socket &sock);

        private:
            int _handle; // platform-specific (epoll fd, kqueue fd, or -1)
        };

        class eventapi {
        public:
             /*HTTP API Events*/
            virtual void RequestEvent(con &curcon,const int tid,ULONG_PTR args)=0;
            virtual void ResponseEvent(con &curcon,const int tid, ULONG_PTR args)=0;
            virtual void ConnectEvent(con &curcon,const int tid, ULONG_PTR args)=0;
            virtual void DisconnectEvent(con &curcon,const int tid, ULONG_PTR args)=0;
            /*memory allocation*/
            virtual void CreateConnection(std::shared_ptr<con> &res)=0;
        protected:
            eventapi(){};
        };

        class event :public eventapi {
        public:
            event(std::vector<netplus::socket*> serversockets, int timeout=1000);

            void runEventloop(ULONG_PTR args=0);

            static void requestStop();

            virtual ~event();

            static inline std::atomic<bool> Restart{false};
	        static inline std::atomic<bool> Running{true};

            int                      threads;
        protected:
            event(const event &src);
        private:
            std::vector<netplus::socket*> _ServerSockets;
            int           _Timeout;
            int           _pollFD;
            friend class EventWorker;
        };
};
