/* Copyright 2020, Michele Santullo
 * This file is part of orotool.
 *
 * Orotool is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Orotool is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Orotool.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "timer_base.hpp"
#include "eventia_thread_pool.hpp"
#include "oro/api.hpp"
#include "oro/originsdb.hpp"
#include <cassert>
#include <iostream>
#include <chrono>

namespace duck {

namespace {
	[[gnu::pure]]
	unsigned long time_interval (const oro::Header& header, double min_wait, double extra) {
		//The way I understand retry_after as returned by the origins server is
		//that it's just how long you need to wait before all your retries
		//reset to the max. When you get for example to 5/8 retries, even if you
		//wait some time that number will never go back to 6. At some point it
		//will just resent to 8. You can do as many as 8 calls one after the
		//other too, it simply means that until the counter resets back to 8 you
		//just won't be able to do anything else.
		const double rem = static_cast<double>(header.rate_limit_remaining);
		const auto& retry_after = header.retry_after;
		const double ra = static_cast<double>(retry_after);

		const auto wait = static_cast<unsigned long>(ra / (rem + 1.0) + 0.5);
		const auto extra_sec = (wait == retry_after ? 1UL : 0UL);
		return std::max(wait + extra_sec + extra, min_wait);
	}

	oro::Timestamp calc_next_update (const oro::Header& header, double min_wait, double extra) {
		oro::Timestamp ret;
		ret.ts =
			std::chrono::time_point_cast<oro::timestamp_t::duration>(std::chrono::system_clock::now()) +
			std::chrono::seconds(time_interval(header, min_wait, extra));
		return ret;
	}

	double initial_timer (oro::OriginsDB& db, oro::DBOperation op, double min_wait) {
		using std::chrono::duration_cast;
		using std::chrono::duration;
		using std::chrono::seconds;

		auto now = std::chrono::system_clock::now();
		auto next_time = db.next_access_time(op);
		duration<double> diff = duration_cast<seconds>(next_time.ts - now);
		const auto retval = std::max(min_wait, std::min(3600.0 * 24.0 * 10.0, diff.count()));
		return retval;
	}
} //unnamed namespace

TimerBase::TimerBase (
	const eve::Context& ctx,
	oro::DBOperation type,
	const TimerSettings& settings,
	EventiaThreadPool* pool,
	oro::Api* oro_api,
	oro::OriginsDB* db
) :
	eve::Timer(initial_timer(*db, type, 2.0), ctx),
	m_extra_delay(settings.extra_delay),
	m_min_wait(settings.min_wait),
	m_err_timeout(settings.err_timeout),
	m_pool(pool),
	m_oro_api(oro_api),
	m_db(db),
	m_source_store_mode(settings.src_store_mode),
	m_err_retries(settings.err_retries)
{
	assert(m_pool);
	assert(m_oro_api);
}

void TimerBase::on_timer() {
	m_pool->submit(&TimerBase::fetch_data, this, m_source_store_mode);
}

void TimerBase::set_next_timer (const oro::Header& header) {
	const unsigned long next_timer = time_interval(header, m_min_wait, m_extra_delay);
	this->set_timer(static_cast<double>(next_timer));
}

EventiaThreadPool& TimerBase::pool() {
	assert(m_pool);
	return *m_pool;
}

oro::Api& TimerBase::oro_api() {
	assert(m_oro_api);
	return *m_oro_api;
}

oro::OriginsDB& TimerBase::db() {
	assert(m_db);
	return *m_db;
}

void TimerBase::reset_db_access_time (oro::DBOperation op) {
	oro::Timestamp ts;
	ts.ts =
		std::chrono::time_point_cast<oro::timestamp_t::duration>(std::chrono::system_clock::now()) +
		std::chrono::seconds(static_cast<unsigned long>(m_min_wait));
	db().update_access_time(ts, op);
}

void TimerBase::update_db (const oro::Shops& shops, const oro::Header& header, const oro::Source& source) {
	db().update(shops, calc_next_update(header, m_min_wait, m_extra_delay), source);
}

void TimerBase::update_db (const oro::Items& items, const oro::Header& header, const oro::Source& source) {
	db().update(items, calc_next_update(header, m_min_wait, m_extra_delay), source);
}

void TimerBase::update_db (const oro::Icons& icons, const oro::Header& header, const oro::Source& source) {
	db().update(icons, calc_next_update(header, m_min_wait, m_extra_delay), source);
}

void TimerBase::update_db (const oro::Creators& creators, const oro::Header& header, const oro::Source& source) {
	db().update(creators, calc_next_update(header, m_min_wait, m_extra_delay), source);
}

double TimerBase::error_timeout() const noexcept {
	return m_err_timeout;
}

unsigned int TimerBase::error_retries() const noexcept {
	return m_err_retries;
}

} //namespace duck
