// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use std::fs;
use std::fs::{File};
use std::io::{Read, Write};
use std::path::MAIN_SEPARATOR_STR;

use crate::metadata::{*};
mod metadata;

// Learn more about Tauri commands at https://tauri.app/v1/guides/features/command
#[tauri::command]
fn greet(name: &str) -> String {
    format!("Hello, {}! You've been greeted from Rust!", name)
}

fn main() {
    tauri::Builder::default()
        .invoke_handler(tauri::generate_handler![greet, save, save_bundle])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

#[tauri::command]
fn save(metadata: Metadata, path: String) -> String {
    let file_path: String;
    if path.ends_with(MAIN_SEPARATOR_STR) {
        file_path = path + "ComicInfo.xml";
    }
    else {
        file_path = path + MAIN_SEPARATOR_STR + "ComicInfo.xml";
    }
    metadata.save_to_xml(&file_path);
    file_path
}

#[tauri::command]
fn save_bundle(bundle_dir: String, metadata_file_path: String, save_path: String) -> String {
    let comic_book_zip = File::create(&save_path).unwrap();
    let mut zip_writer = zip::ZipWriter::new(comic_book_zip);

    let options = zip::write::FileOptions::default().compression_method(zip::CompressionMethod::Stored);

    let mut file_list: Vec<String> = Vec::new();

    file_list.push(metadata_file_path);

    let directory_contents = fs::read_dir(bundle_dir.clone()).unwrap();

    directory_contents.for_each(|entry| file_list.push(entry.unwrap().path().to_str().unwrap().to_string()));

    for file in file_list {
        zip_writer.start_file(file.clone().split(MAIN_SEPARATOR_STR).last().unwrap(), options).unwrap();
        let mut file = File::open(file).unwrap();
        let mut buffer = Vec::new();

        file.read_to_end(&mut buffer).unwrap();

        zip_writer.write(&*buffer).unwrap();
    }

    zip_writer.finish().unwrap();
    return bundle_dir
}