/*
 *  Copyright (C) 2006-2019  Ronald Blankendaal
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */
package org.dbgl.gui.thread;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.IntStream;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.dbgl.constants.Constants;
import org.dbgl.model.GamePack;
import org.dbgl.model.aggregate.Profile;
import org.dbgl.model.entity.GamePackEntry;
import org.dbgl.model.repository.ProfileRepository;
import org.dbgl.service.SettingsService;
import org.dbgl.util.FilesUtils;
import org.dbgl.util.StringRelatedUtils;
import org.dbgl.util.archive.SevenzipExtractFilesCallback;
import org.dbgl.util.archive.SevenzipUtils;
import org.dbgl.util.archive.ZipUtils;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.widgets.Text;
import SevenZip.MyRandomAccessFile;
import SevenZip.Archive.IInArchive;
import SevenZip.Archive.SevenZip.Handler;


public class ImportThread extends UIThread<GamePackEntry> {

	private File zipfile_;
	private GamePack gamePack_;
	private boolean useExistingConf_;
	private boolean importFullSettings_;
	private boolean customValues_;
	private boolean customFields_;
	private boolean sevenzip_;
	private IInArchive zArchive_;
	private Map<Integer, File> sevenzipDstFileMap_;

	public ImportThread(Text log, ProgressBar progressBar, Label status, File zipfile, GamePack packageData, boolean useExistingConf, boolean fullSettings, boolean customValues, boolean customFields)
			throws IOException, SQLException {
		super(log, progressBar, status, true);

		zipfile_ = zipfile;
		gamePack_ = packageData;
		useExistingConf_ = useExistingConf;
		importFullSettings_ = fullSettings;
		customValues_ = customValues;
		customFields_ = customFields;

		sevenzip_ = zipfile.getPath().toLowerCase().endsWith(FilesUtils.ARCHIVES[1]);
		sevenzipDstFileMap_ = new TreeMap<>();
		long bytes = 0;
		if (sevenzip_) {
			MyRandomAccessFile istream = new MyRandomAccessFile(zipfile.getPath(), "r");
			zArchive_ = new Handler();
			if (zArchive_.Open(istream) != 0)
				throw new IOException(text_.get("general.error.opensevenzip", new Object[] {zipfile.getPath()}));
			for (int i = 0; i < zArchive_.size(); i++)
				bytes += zArchive_.getEntry(i).getSize();
		} else {
			for (GamePackEntry entry: gamePack_.getEntries()) {
				if (gamePack_.isCapturesAvailable())
					bytes += ZipUtils.extractedSizeInBytes(zipfile, entry.getArchiveCapturesDir());
				if (gamePack_.isMapperfilesAvailable() && entry.hasMapper())
					bytes += ZipUtils.extractedSizeInBytes(zipfile, entry.getArchiveMapper());
				if (gamePack_.isGamedataAvailable())
					bytes += ZipUtils.extractedSizeInBytes(zipfile, entry.getArchiveGameDir());
			}
		}

		setObjects(gamePack_.getEntries());
		setTotal(bytes);
	}

	public String work(GamePackEntry entry) throws IOException, SQLException {
		displayTitle(text_.get("dialog.import.importing", new Object[] {getTitle(entry)}));

		Profile prof = entry.getProfile();

		if (!customValues_)
			prof.resetAllCustomValues();

		if (!gamePack_.isNativecommandsAvailable())
			prof.resetNativeCommands();

		prof.loadConfigurationData(text_, importFullSettings_ ? entry.getFullConfig(): entry.getIncrConfig(), zipfile_);

		if (gamePack_.isMapperfilesAvailable() && entry.hasMapper())
			prof.setValue("sdl", "mapperfile", entry.getNewMapper().getName());

		// fix paths for profile autoexec, links, setup, altexe
		prof.setBaseDir(entry.getBaseDir());

		prof = new ProfileRepository().add(prof, useExistingConf_);

		if (gamePack_.isCapturesAvailable()) {
			if (sevenzip_) {
				sevenzipDstFileMap_.putAll(SevenzipUtils.findEntries(zArchive_, entry.getArchiveCapturesDir(), prof.getCanonicalCaptures()));
			} else {
				try {
					ZipUtils.extractDirInZip(zipfile_, entry.getArchiveCapturesDir(), prof.getCanonicalCaptures(), this);
					messageLog_.append(PREFIX_OK).append(text_.get("dialog.import.notice.extractedcaptures", new Object[] {prof.getCanonicalCaptures()})).append('\n');
				} catch (IOException e) {
					messageLog_.append(PREFIX_ERR).append(text_.get("dialog.import.error.capturesextraction", new Object[] {StringRelatedUtils.toString(e)})).append('\n');
				}
			}
		}

		if (gamePack_.isGamedataAvailable()) {
			File canonicalFullDir = entry.getCanonicalFullDir();
			if (!canonicalFullDir.exists()) {
				FilesUtils.createDir(canonicalFullDir);
				messageLog_.append(PREFIX_OK).append(text_.get("dialog.import.notice.createddir", new Object[] {canonicalFullDir})).append('\n');
			}
			if (sevenzip_) {
				sevenzipDstFileMap_.putAll(SevenzipUtils.findEntries(zArchive_, entry.getArchiveGameDir(), canonicalFullDir));
			} else {
				try {
					ZipUtils.extractDirInZip(zipfile_, entry.getArchiveGameDir(), canonicalFullDir, this);
					messageLog_.append(PREFIX_OK).append(text_.get("dialog.import.notice.extractedgamedata", new Object[] {canonicalFullDir})).append('\n');
				} catch (IOException e) {
					throw new IOException(text_.get("dialog.import.error.gamedataextraction", new Object[] {StringRelatedUtils.toString(e)}), e);
				}
			}
		}

		if (gamePack_.isMapperfilesAvailable() && entry.hasMapper()) {
			File dstFile = entry.getNewMapper();
			if (sevenzip_) {
				Map.Entry<Integer, File> szEntry = SevenzipUtils.findEntry(zArchive_, entry.getArchiveMapper(), dstFile);
				if (szEntry != null)
					sevenzipDstFileMap_.put(szEntry.getKey(), szEntry.getValue());
			} else {
				try {
					ZipUtils.extractFileInZip(zipfile_, entry.getArchiveMapper(), dstFile, this);
					messageLog_.append(PREFIX_OK).append(text_.get("dialog.import.notice.extractedmapperfile", new Object[] {dstFile})).append('\n');
				} catch (IOException e) {
					messageLog_.append(PREFIX_ERR).append(text_.get("dialog.import.error.mapperfileextraction", new Object[] {StringRelatedUtils.toString(e)})).append('\n');
				}
			}
		}

		messageLog_.append(PREFIX_OK).append(
			text_.get("dialog.import.notice.createddbentry", new Object[] {prof.getId(), prof.getConfigurationFile(), prof.getCapturesString(), prof.getDosboxVersion().getTitle()})).append('\n');

		return null;
	}

	public String getTitle(GamePackEntry entry) {
		return entry.getProfile().getTitle();
	}

	public void preFinish() throws IOException {
		if (customFields_) {
			for (int i = 0; i < Constants.EDIT_COLUMN_NAMES; i++) {
				String customField = gamePack_.getCustomFieldTitles()[i];
				if (StringUtils.isNotBlank(customField) && !customField.equalsIgnoreCase("Custom" + (i + 1)))
					SettingsService.getInstance().setValue("gui", "custom" + (i + 1), gamePack_.getCustomFieldTitles()[i]);
			}
		}
		if (sevenzip_) {
			int[] entryIdsToBeExtracted_ = ArrayUtils.toPrimitive(sevenzipDstFileMap_.keySet().toArray(new Integer[0]));
			SevenzipExtractFilesCallback extractCallback = new SevenzipExtractFilesCallback(this, zArchive_, sevenzipDstFileMap_);
			zArchive_.Extract(entryIdsToBeExtracted_, entryIdsToBeExtracted_.length, IInArchive.NExtract_NAskMode_kExtract, extractCallback);
			IntStream.of(entryIdsToBeExtracted_).forEach(id -> FilesUtils.setLastModified(sevenzipDstFileMap_.get(id), zArchive_.getEntry(id).getTime()));
			zArchive_.close();
		}
	}
}