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
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
use colored::*;
use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
#[allow(unused_imports)]
use log::{debug, error, info, trace, warn};
use std::path::PathBuf;
use std::thread;
use std::thread::JoinHandle;

use df_st_core::config::RootConfig;
use df_st_core::*;
use df_st_db::*;
use df_st_legends::*;
use df_st_legends_plus::*;

mod find_files;
mod unknown_items;
use find_files::{
    find_missing_files, find_missing_images, find_site_map_images, get_file_prefix,
    get_world_info_from_filename,
};
use unknown_items::{print_unknown_elements_list, print_unknown_list_combined};

pub fn parse_xml_files(file: &PathBuf) -> DFWorld {
    // Create Core world
    let mut df_world_core: DFWorld = DFWorld::new();

    let filenames = find_missing_files(&file);
    if !filenames.some_found() {
        error!("Could not find any files. No legends file to parse.");
        return df_world_core;
    }

    info!("Parsing data ...");
    let m = MultiProgress::new();
    let sty = ProgressStyle::default_bar()
        .template(
            "{prefix:<18}: [{elapsed_precise}] {msg:>1}{spinner:.yellow} [{bar:50.green}] \
            {bytes}/{total_bytes} (eta: {eta})",
        )
        .progress_chars("=> ");

    let start = std::time::Instant::now();

    let mut legends_thread_option: Option<JoinHandle<thread::Result<DFWorldLegends>>> = None;
    if let Some(legends_file) = filenames.legends {
        let progress_bar = m.add(ProgressBar::new(100));
        progress_bar.set_style(sty.clone());
        progress_bar.set_prefix("legends.xml");
        legends_thread_option = Some(thread::spawn(move || -> thread::Result<DFWorldLegends> {
            // info!("Parsing legends.xml ...");
            let df_world_legends = parse_legends(&legends_file, progress_bar);
            // info!("Parsing legends.xml {}", "Done".green());
            Ok(df_world_legends)
        }));
    }

    let mut legends_plus_thread_option: Option<JoinHandle<thread::Result<DFWorldLegendsPlus>>> =
        None;
    if let Some(legends_plus_file) = filenames.legends_plus {
        let progress_bar = m.add(ProgressBar::new(100));
        progress_bar.set_style(sty);
        progress_bar.set_prefix("legends_plus.xml");
        legends_plus_thread_option = Some(thread::spawn(
            move || -> thread::Result<DFWorldLegendsPlus> {
                // info!("Parsing legends_plus.xml ...");
                let df_world_legends_plus = parse_legends_plus(&legends_plus_file, progress_bar);
                // info!("Parsing legends_plus.xml {}", "Done".green());
                Ok(df_world_legends_plus)
            },
        ));
    }

    // Parse other files on main thread
    // println!("\tParsing world_history.txt ...");
    // parse_world_history(&format!("../world/{}-world_history.txt",filenameprefix));
    // println!("\tParsing world_history.txt {}", "Done".green());
    // println!("\tParsing world_sites_and_pops.txt ...");
    // parse_world_site_and_pops(&format!("../world/{}-world_sites_and_pops.txt",filenameprefix));
    // println!("\tParsing world_sites_and_pops.txt {}", "Done".green());

    // merge back everything to main thread
    let mut df_world_legends: DFWorldLegends = DFWorldLegends::new();
    let mut df_world_legends_plus: DFWorldLegendsPlus = DFWorldLegendsPlus::new();
    m.join().unwrap();
    if let Some(legends_thread) = legends_thread_option {
        df_world_legends = match legends_thread.join() {
            Ok(result) => match result {
                Ok(result) => result,
                Err(err) => {
                    error!("legends thread result failed: {:?}", err);
                    warn!(
                        "The legends thread failed. We can recover from this but the \
                        legends file will not be imported. Please report the error above."
                    );
                    DFWorldLegends::default()
                }
            },
            Err(err) => {
                error!("legends thread failed: {:?}", err);
                warn!(
                    "The legends thread failed. We can recover from this but the \
                    legends file will not be imported. Please report the error above."
                );
                DFWorldLegends::default()
            }
        };
    }
    if let Some(legends_plus_thread) = legends_plus_thread_option {
        df_world_legends_plus = match legends_plus_thread.join() {
            Ok(result) => match result {
                Ok(result) => result,
                Err(err) => {
                    error!("legends_plus thread result failed: {:?}", err);
                    warn!(
                        "The legends_plus thread failed. We can recover from this but the \
                        legends_plus file will not be imported. Please report the error above."
                    );
                    DFWorldLegendsPlus::default()
                }
            },
            Err(err) => {
                error!("legends_plus thread failed: {:?}", err);
                warn!(
                    "The legends_plus thread failed. We can recover from this but the \
                    legends_plus file will not be imported. Please report the error above."
                );
                DFWorldLegendsPlus::default()
            }
        };
    }

    // Check if there are tags that are not implemented
    print_unknown_elements_list(&df_world_legends, "legends.xml");
    print_unknown_list_combined(&df_world_legends, "legends.xml");
    print_unknown_elements_list(&df_world_legends_plus, "legends_plus.xml");
    print_unknown_list_combined(&df_world_legends_plus, "legends_plus.xml");

    // println!("{:#?}", df_world_legends);
    // println!("{:#?}", df_world_legends_plus.mountain_peaks);
    info!("Parsing data {}", "Done".green());
    info!("Parsing duration: {:?}", start.elapsed());

    info!("Merging data ...");
    let start = std::time::Instant::now();
    // Add data to Core world
    df_world_core.add_missing_data(&df_world_legends);
    // Try to save a bit of memory
    drop(df_world_legends);
    df_world_core.add_missing_data(&df_world_legends_plus);
    info!("Merging data {}", "Done".green());
    info!("Merging duration: {:?}", start.elapsed());

    info!(
        "Combined items include:\n{}",
        df_world_core.list_containt_counts()
    );
    df_world_core
}

pub fn parse_and_store_xml(file: &PathBuf, config: &RootConfig, world_id: i32) {
    let pool = df_st_db::establish_connection(&config).expect("Failed to connect to database.");
    let conn = pool.get().expect("Couldn't get db connection from pool.");

    // TODO check if world id is used, if already used display this.
    let filename = get_file_prefix(&file);
    let mut df_world = parse_xml_files(&file);
    // trace!("{:#?}", df_world);

    // Add missing ID's
    info!("Create missing ID's ...");
    let start = std::time::Instant::now();
    df_world = df_world.add_missing_ids();
    info!("Create missing ID's {}", "Done".green());
    info!("Create missing ID's duration: {:?}", start.elapsed());

    df_world = df_world.create_reference_links();

    info!("Storing data ...");
    info!(
        "NOTE: The `Historical Events` (HE) usually take a bit longer to store \
        (there are just more of them)."
    );
    let start = std::time::Instant::now();
    // store in db objects
    let mut df_world_db: DBDFWorld = DBDFWorld::new();
    // Add data to DB world
    df_world_db.add_missing_data(&df_world);
    // Add additional info from filename
    if let Some(filename) = filename {
        let df_world_info = get_world_info_from_filename(&filename, world_id);
        df_world_db.world_info.add_missing_data(&df_world_info);
    }
    // Set world_id for all items
    df_world_db.set_world_id(world_id);
    // println!("{:#?}", df_world_db);
    let progress_bar = ProgressBar::new(100);
    progress_bar.set_style(ProgressStyle::default_spinner().template(
        "{prefix:<18}: [{elapsed_precise}] [{bar:40.green}] {pos:>2}/{len:2} \
        (eta: {eta}) {wide_msg}",
    ));
    progress_bar.set_prefix("Storing in DB");

    // store db objects
    df_world_db.insert_into_db(&conn, Some(progress_bar));

    info!("Storing data {}", "Done".green());
    info!("Storing data duration: {:?}", start.elapsed());
}

pub fn parse_world_map_images(file: &PathBuf, config: &RootConfig, world_id: i32) {
    let pool = df_st_db::establish_connection(&config).expect("Failed to connect to database.");
    let conn = pool.get().expect("Couldn't get db connection from pool.");

    info!("Loading map images ...");
    let file_names = find_missing_images(&file);
    if !file_names.some_found() {
        warn!("Could not find any files. No world map images to parse.");
        return;
    }
    let world_images = df_st_image_maps::parse_world_map_images(file_names);
    info!("Loading map images {}", "Done".green());

    info!("Storing data ...");
    let start = std::time::Instant::now();
    // store in db objects
    let mut world_images_db: df_st_db::WorldMapImages = df_st_db::WorldMapImages::new();
    // Add data to DB world
    world_images_db.add_missing_data(&world_images);
    // Set world_id for all items
    world_images_db.set_world_id(world_id);
    // println!("{:#?}", df_world_db);
    let progress_bar = ProgressBar::new(100);
    progress_bar.set_style(ProgressStyle::default_spinner().template(
        "{prefix:<18}: [{elapsed_precise}] [{bar:40.green}] {pos:>2}/{len:2} \
        (eta: {eta}) {wide_msg}",
    ));
    progress_bar.set_prefix("Storing in DB");

    // store db objects
    world_images_db.insert_into_db(&conn, progress_bar);

    info!("Storing data {}", "Done".green());
    info!("Storing data duration: {:?}", start.elapsed());
}

pub fn parse_site_map_images(file: &PathBuf, config: &RootConfig, world_id: i32) {
    let pool = df_st_db::establish_connection(&config).expect("Failed to connect to database.");
    let conn = pool.get().expect("Couldn't get db connection from pool.");

    info!("Loading site map images ...");
    let file_names = find_site_map_images(&file);
    if !file_names.some_found() {
        warn!("Could not find any files. No site map images to parse.");
        return;
    }
    let site_map_images = df_st_image_site_maps::parse_site_map_images(file_names);
    info!("Loading site map images {}", "Done".green());

    info!("Storing data ...");
    let start = std::time::Instant::now();
    // store in db objects
    let mut site_map_images_db: df_st_db::SiteMapImages = df_st_db::SiteMapImages::new();
    // Add data to DB world
    site_map_images_db.add_missing_data(&site_map_images);
    // Set world_id for all items
    site_map_images_db.set_world_id(world_id);
    // println!("{:#?}", df_world_db);
    let progress_bar = ProgressBar::new(100);
    progress_bar.set_style(ProgressStyle::default_spinner().template(
        "{prefix:<18}: [{elapsed_precise}] [{bar:40.green}] {pos:>2}/{len:2} \
        (eta: {eta}) {wide_msg}",
    ));
    progress_bar.set_prefix("Storing in DB");

    // store db objects
    site_map_images_db.insert_into_db(&conn, progress_bar);

    info!("Storing data {}", "Done".green());
    info!("Storing data duration: {:?}", start.elapsed());
}