#ifndef SAVE_THREAD_H
#define SAVE_THREAD_H
#include <QThread>
#include <QDebug>
#include <QDateTime>
#include "SyncQueue.h"
#include "common.h"
#include <iostream>
#include <string>
#include <vector>

#include <qdir.h>

#include <opencv2/opencv.hpp>
#include <opencv2/imgproc/types_c.h>

class SaveThread : public QThread
{
        Q_OBJECT
signals:
		
		
public:
		SaveThread(QObject *parent = 0): QThread(parent)
        {

        }
		~SaveThread()
        {
			stop();
			p_save_queue->put(std::make_pair("", cv::Mat()));
			quit();
			wait();
        }

        void init(SyncQueue<std::pair<std::string, cv::Mat> > *p_save_queue_)
        {
			p_save_queue = p_save_queue_;
			b_quit = false;
        }
        void start_work()
        {
             start(HighestPriority);
        }
		void stop()
		{
			b_quit = true;
		}
protected:
    void run()
        {
            while (!b_quit) {
				cv::Mat image;
				std::pair<std::string, cv::Mat> element;
				p_save_queue->take(element);
				std::string file_name = element.first;
				//std::cout << file_name << std::endl;
				image = element.second;
				if (image.data)
				{
					std::size_t found = file_name.find_last_of("/\\");
					std::string dir_path = file_name.substr(0, found);
					check_save_dir(dir_path);
					bool b_save = cv::imwrite(file_name, image);
				}
            }
        }
	void check_save_dir(std::string dir_path)
	{
		bool b_find = false;
		for (int i = 0; i < vec_save_dirs.size(); i++)
		{
			if (dir_path == vec_save_dirs[i])
			{
				b_find = true;
			}
		}
		if (!b_find)
		{
			QString dir_str = QString::fromStdString(dir_path);
			QDir dir;
			if (!dir.exists(dir_str))
			{
				dir.mkpath(dir_str);
			}
			vec_save_dirs.push_back(dir_path);
		}
	}
public:
	bool b_quit;
	std::vector<std::string> vec_save_dirs;
	SyncQueue<std::pair<std::string, cv::Mat> > *p_save_queue;
};
#endif
