aboutsummaryrefslogtreecommitdiff
path: root/oop2eindopdr/ZipExport.cpp
blob: eb0d60faba977482b82f2a6ddc27bc1d9be15d81 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <csv2/reader.hpp>
#include <fstream>
#include <iostream>
#include <zip.h>

#include "ZipExport.h"
#include "Pokedex.h"
#include "PokemonCard.h"

ZipExport::ZipExport() { }
ZipExport::~ZipExport() { }

ZipExport::ZipExport(Pokedex* pokedex, std::string input_csv, std::string output_zip) {
	set_pokedex(pokedex);
	import_csv(input_csv);
	export_zip(output_zip);
}

void ZipExport::set_pokedex(Pokedex* pokedex) {
	this->pokedex = pokedex;
}

void ZipExport::export_zip(std::string filename) {
	this->zip_path = filename;

	std::vector<zip_source*> zip_srcs;
	zip_t* zip = zip_open(this->zip_path.c_str(), ZIP_CREATE | ZIP_EXCL, nullptr);

	std::string csv_content = "id,value\n";

	for (std::string card_id : this->id_list) {
		PokemonCard* card = this->pokedex->get_card_by_id(card_id);
		if (card == nullptr) {
			csv_content.append(card->id + "," + "???" + "\n");
			continue;
		}
		card->fetch_market_value();

		char* value_str;
		asprintf(&value_str, "%.2f", card->value);
		csv_content.append(card->id + "," + std::string(value_str) + "\n");
		free(value_str);

		zip_source* image = zip_source_file(zip, card->image_location_hires().c_str(), 0, 0);
		zip_file_add(zip, std::string(card->id + ".png").c_str(), image, 0);
		zip_srcs.push_back(image);
	}

	zip_source* csv_file = zip_source_buffer(zip, csv_content.data(), csv_content.size(), 0);
	zip_file_add(zip, "cards.csv", csv_file, 0);

	zip_close(zip);
}

void ZipExport::import_csv(std::string filename) {
	this->csv_path = filename;

	csv2::Reader<csv2::delimiter<','>,
		csv2::quote_character<'"'>,
		csv2::first_row_is_header<true>,
		csv2::trim_policy::trim_whitespace> csv;

	if (csv.mmap(this->csv_path)) {
		for (const auto row: csv) {
			for (const auto cell: row) {
				std::string value;
				cell.read_value(value);
				this->id_list.push_back(value);
			}
		}
	} else {
		std::cout << "parsing csv failed!" << std::endl;
		exit(EXIT_FAILURE);
	}
}