#ifndef _Utils_H_
#define _Utils_H_

#include <vector>
#include <string>
#include <sstream>
#include <string.h>
#include <iomanip>
#include <functional>
#include <thread>
using namespace std;

class Utils
{
public:
	static std::string toHex(std::vector<unsigned char>& s, int len = 0);
	static std::string toHex(const std::string& s);
	static std::string fromHex(const std::string& hexstr);
	static string fromHexText(string s);
	static string toHexText(string s, string d = " ");

	static int64_t hexBinToInt(const string& str, bool swap = false);
	static int hexStrToInt(const string& str);

	static string toStr(int v);
	static string toStr(float v, int precision = 2);
	static string toStr(double v, int precision = 2);

	static int toInt(const std::string& str);
	static float toFloat(const string& str);
	static double toDouble(const string& str);


	template<typename T>
	static void append_bytes(vector<unsigned char>& dest, const T& src, int len)
	{
		int start = static_cast<int>(dest.size());
		dest.resize(start + len);
		memcpy_s(&dest[start], len, &src, len);
	}

	// 获取当前时间的时间戳（秒）
	static int64_t time(std::string s="");
	// 获取当前时间的格式字符串
	static string timeStr(int64_t ts=0, std::string fmt = "%Y-%m-%d %H:%M:%S");
	// 获取当前日期的时间戳（秒）
	static int64_t date();
	// 获取当前日期的格式字符串
	static string dateStr(int64_t ts = 0, std::string fmt = "%Y-%m-%d %H:%M:%S");

	static string timeStrMS(std::string fmt = "%Y-%m-%d %H:%M:%S");
	//static string timeStr(int64_t ts, std::string fmt = "%Y-%m-%d %H:%M:%S");

	//static int64_t time(string dt="", int zone = 0);

	//static string time_to_string(int64_t dt, std::string fmt="%Y-%m-%d %H:%M:%S");
	//static bool time_string_to_tm(string dt, std::tm& t);

	static int64_t timeDaySeconds();

    std::string duration_str(int64_t t)
    {
        auto h = t / 3600;
        auto m = (t % 3600) / 60;
        auto s = (t % 3600) % 60;
        std::string str = std::to_string(s) + "秒";
        if (m > 0 || h > 0)
        {
            str = std::to_string(m) + "分" + str;
        }
        if (h > 0)
        {
            str = std::to_string(h) + "小时" + str;
        }
        return str;
    }

	static unsigned short crc16(unsigned char* data, unsigned int len);

	static string gbkToUtf8(string s);
	static string utf8ToGbk(string s);

	static void sleepMS(int ms);

	static int random(int min, int max);

	static void split(string buf, string c, vector<string>& res);

	static std::string readFile(std::string filename);
};

class TimeTick
{
public:
	TimeTick(int t=0)
	{
		if (t !=0) { tickMS_ = Utils::time(); }
	}

	bool elapse(int64_t second, bool reset = true)
	{
		auto tickNow = Utils::time();
		bool ret = tickNow - tickMS_ > second;
		if (ret && reset) { tickMS_ = tickNow; }
		return ret;
	}

	void reset() { tickMS_ = Utils::time(); }

public:
	int64_t tickMS_ = 0;
};

#endif // !!! _Utils_H_
