#ifndef SH_DATABASE_STORAGE_H
#define SH_DATABASE_STORAGE_H

#include <QDebug>
#include <QSqlDatabase>
#include <QSqlRecord>
#include <QSqlQuery>
#include <QSqlDriver>
#include <QSqlError>
#include <blockitem.h>
#include <blockbusitem.h>
#include "database_structs.h"

const QString mysql_user_read  = "shs_guest";
const QString mysql_user_write = "shs"      ;
const QString mysql_database   = "shs"      ;

TableRow TableRow_fromRecord(const QSqlRecord & r);

void BusType_save(const BusType & b, const QSqlDatabase & base);
void BusType_load(BusType & b, const QSqlRecord & r);

void BlockType_save(const BlockType & b, const QSqlDatabase & base);
void BlockType_load(BlockType & b, const QSqlRecord & r);


class SHDatabaseStorage {
public:
	explicit SHDatabaseStorage();
	~SHDatabaseStorage();

	bool load(QSqlDatabase & base);
	void save(QSqlDatabase & base);
	void clear() {unload();}

	BlockType getBlockData(int id) const {return block_types.value(id);}
	BlockType getBlockData(BlockItem * block) const {return getBlockData(block->data(SH_Block_ID).toInt());}
	void loadBus(BlockBusItem * bus);
	void loadBlock(BlockItem * block, bool with_model = true);
	void loadBlockModel(BlockItem * block);
	void prepareBlock(BlockItem * block);
	BlockItem * srcBlock(const BlockItem * block) const;
	BusType srcBus(const BlockBusItem * bus) const;
	
	static void initDatabase(QSqlDatabase & base);
	static void checkTable(QSqlDatabase & base, const QString & tname, QString tinit);

	static void loadBlockPinsProperties(BlockItem * block, const QMap<QString, PropertyStorage> & db);
	static PropertyStorage loadBlockProperties(BlockItem * block, const PropertyStorage & db, const QString & plugin_name);
	static PropertyStorage loadPinProperties(BlockItemPin * pin, PropertyStorage sp, const QString & plugin_name);
	static PropertyStorage loadBusProperties(BlockBusItem * bus, const PropertyStorage & db, const QString & plugin_name);

	PIMap<int, BusType> bus_types;
	PIMap<int, BlockType> block_types;
	PIMap<int, BlockItem * > src_blocks;
	PIMap<int, TableRow> table_vendors, table_groups;
	
private:
	void unload();
	void load_v0(QSqlDatabase & base);
	void load_v1(QSqlDatabase & base);
	
};


#endif
