/**
 * File:   SessionSynchronizeWorker.h
 * Author: Alexander Ksenofontov <aksenofo@yahoo.ru>
 *
 * Created on August 15, 2016, 14:13 PM
 */

#pragma once

#include <nan.h>
#include "session.h"
#include "declarations.h"

class Environment;

class SynchronizeWorker: public Nan::AsyncProgressWorker {

	struct data_pulse {
		data_pulse()
			: protocol_()
			, progress_(0)
			, file_()
		{}

		std::string protocol_; // "HTTP", "TORRENT"
		double progress_;

		std::string file_;
	};

public:

    SynchronizeWorker(const v8::Persistent<v8::Object, v8::CopyablePersistentTraits<v8::Object>>& owner_, 
                            Nan::Callback *periodical, Nan::Callback *finished,
			    const Session::remote_info& ri);

    virtual ~SynchronizeWorker();

    void Execute (const Nan::AsyncProgressWorker::ExecutionProgress& progress);

    void HandleProgressCallback(const char *data, size_t size);

    void HandleOKCallback();

    int64_t compare();

    int64_t load_dir_list();

	static void send_progress(const Nan::AsyncProgressWorker::ExecutionProgress& progress, SynchronizeWorker::data_pulse* dp);

    std::shared_ptr<std::vector<std::tuple<std::string, uint64_t, std::string>>> 
		detect_failed(const Nan::AsyncProgressWorker::ExecutionProgress& progress, uint64_t& total);

    std::shared_ptr<std::vector<std::tuple<std::string, uint64_t, std::string>>>
	    HTTPsync(const Nan::AsyncProgressWorker::ExecutionProgress& progress, 
			     std::shared_ptr<std::vector<std::tuple<std::string, uint64_t, std::string>>>& items);

    void TorrentSync(const Nan::AsyncProgressWorker::ExecutionProgress& progress);

private:

    v8::Persistent<v8::Object, v8::CopyablePersistentTraits<v8::Object>> owner_;

    Session::remote_info ri_;

    int error_;

	uint64_t total_;

    std::shared_ptr<std::vector<std::tuple<std::string, uint64_t, std::string>>> items_;

    Nan::Callback *periodical_;
};


extern std::shared_ptr<Environment> torrent_session;
