function Window_SaveType() {
	this.initialize(...arguments);
}

(function () {
	//#####################　セーブの背景変える　#####################
	Scene_File.prototype.createBackground = function () {
		this._backgroundSprite = new Sprite();
		this._backgroundSprite.bitmap = ImageManager.loadSystem("menu_saveload_back");
		this.addChild(this._backgroundSprite);

		this._backgroundTextSprite = new Sprite();
		this._backgroundTextSprite.bitmap = new Bitmap(Graphics.width, Graphics.height);
		var b = this._backgroundTextSprite.bitmap;
		b.fontFace = "serif";
		b.fontSize = 32;
		b.textColor = "#000000";
		if (!this._fromTitle) {
			b.drawTextM("セーブ / ロード", 22, 20, 200, 22, "center");
		} else {
			b.drawTextM("コンティニュ－", 22, 20, 200, 22, "center");
		}
		this.addChild(this._backgroundTextSprite);
	};

	Scene_File.prototype.create = function () {
		Scene_MenuBase.prototype.create.call(this);
		DataManager.loadAllSavefileImages();
		//this.createHelpWindow();
		this.createListWindow();
		//this._helpWindow.setText(this.helpWindowText());
	};

	const Scene_Save_create = Scene_Save.prototype.create;
	Scene_Save.prototype.create = function () {
		Scene_Save_create.call(this);

		var sp = new Sprite();
		sp.bitmap = ImageManager.loadSystem("menu_save_icon");
		sp.x = -240;
		sp.y = -50;
		this._listWindow.addChild(sp);

		// var sp2 = new Sprite();
		// sp2.bitmap = ImageManager.loadSystem("menu_save_category");
		// sp2.x = 0;
		// sp2.y = 0;
		// this.addChild(sp2);

		// this._backgroundTextSprite_cate = new Sprite();
		// this._backgroundTextSprite_cate.bitmap = new Bitmap(Graphics.width, Graphics.height);
		// var b = this._backgroundTextSprite_cate.bitmap;
		// b.fontFace = "serif";
		// b.fontSize = 24;
		// b.textColor = "#000000";
		// b.drawTextM("セーブ", 230, 30, 200, 22, "center");
		// b.drawTextM("ロード", 360, 30, 200, 22, "center");
		// this.addChild(this._backgroundTextSprite_cate);

		const rect = this.categoryWindowRect();
		this._cataWindow = new Window_SaveType(rect, "save");
		this.addChild(this._cataWindow);
	};

	const Scene_Load_create = Scene_Load.prototype.create;
	Scene_Load.prototype.create = function () {
		Scene_Load_create.call(this);

		var sp = new Sprite();
		sp.bitmap = ImageManager.loadSystem("menu_load_icon");
		sp.x = -240;
		sp.y = -50;
		this._listWindow.addChild(sp);

		if (!this._fromTitle) {
			// 	var sp2 = new Sprite();
			// 	sp2.bitmap = ImageManager.loadSystem("menu_load_category");
			// 	sp2.x = 0;
			// 	sp2.y = 0;
			// 	this.addChild(sp2);

			// 	this._backgroundTextSprite_cate = new Sprite();
			// 	this._backgroundTextSprite_cate.bitmap = new Bitmap(Graphics.width, Graphics.height);
			// 	var b = this._backgroundTextSprite_cate.bitmap;
			// 	b.fontFace = "serif";
			// 	b.fontSize = 24;
			// 	b.textColor = "#000000";
			// 	b.drawTextM("セーブ", 230, 30, 200, 22, "center");
			// 	b.drawTextM("ロード", 360, 30, 200, 22, "center");
			// 	this.addChild(this._backgroundTextSprite_cate);

			const rect = this.categoryWindowRect();
			this._cataWindow = new Window_SaveType(rect, "load");
			this.addWindow(this._cataWindow);
		}
	};

	// ページ遷移、タイトルのロード画面だけ弾く
	let fromTitle = false;
	const _Scene_Title_commandContinue = Scene_Title.prototype.commandContinue;
	Scene_Title.prototype.commandContinue = function () {
		fromTitle = true;
		_Scene_Title_commandContinue.call(this);
	};
	const _Scene_Load_create = Scene_Load.prototype.create;
	Scene_Load.prototype.create = function () {
		this._fromTitle = fromTitle;
		_Scene_Load_create.call(this);
		fromTitle = false;
	};

	// #############################################################
	// ################## カテゴリウィンドウ #######################
	// #############################################################
	Scene_File.prototype.categoryWindowRect = function () {
		const wx = 270;
		const wy = -6;
		const ww = 300;
		const wh = 58 + 8;
		return new Rectangle(wx, wy, ww, wh);
	};

	Window_SaveType.prototype = Object.create(Window_Command.prototype);
	Window_SaveType.prototype.constructor = Window_SaveType;

	Window_SaveType.prototype.initialize = function (rect, type) {
		Window_Selectable.prototype.initialize.call(this, rect);
		this.refresh();

		// セーブロードのカテゴリーウィンドウ用
		if (type === "save") {
			this.select(0);
		} else if (type === "load") {
			this.select(1);
		}

		this.activate();

		this.CBR_type = type;
	};

	Window_SaveType.prototype.makeCommandList = function () {
		this.addCommand("セーブ", "prof");
		this.addCommand("ロード", "kaihatu");
	};
	Window_SaveType.prototype.maxCols = function () {
		return 2;
	};

	Window_SaveType.prototype.update = function () {
		Window_Command.prototype.update.call(this);
		//this.setCategory(this.currentSymbol());
	};

	Window_SaveType.prototype.select = function (index) {
		if (SceneManager._nextScene) {
			return;
		}
		if (this.CBR_type === "save") {
			if (index === 1) {
				SceneManager.goto(Scene_Load);
			}
		} else if (this.CBR_type === "load") {
			if (index === 0) {
				SceneManager.goto(Scene_Save);
			}
		}
		this._index = index;
		this.refreshCursor();
		this.callUpdateHelp();
	};

	Window_SaveType.prototype._refreshAllParts = function () {
		this._padding = 0;
		//this._refreshBack();
		//this._refreshFrame();
		this._refreshCursor();
		this._refreshArrows();
		this._refreshPauseSign();
	};

	//カーソルの変更
	Window_SaveType.prototype.loadWindowskin = function () {
		this.windowskin = ImageManager.loadSystem("Window");
		this.menu_item_skin = ImageManager.loadSystem("menu_item_categoly_select");
		this.menu_cursor_skin = ImageManager.loadSystem("menu_item_categoly_cursor");

		if (!this.menu_item_skin.isReady()) {
			this.menu_item_skin.addLoadListener(() => {
				this.refresh(); // 画像がロードされたら再描画
			});
			return;
		}
	};

	Window_SaveType.prototype.lineHeight = function () {
		return 58;
	};

	Window_SaveType.prototype._refreshCursor = function () {
		const drect = this._cursorRect.clone();
		const srect = { x: 0, y: 0, width: 126, height: 58 };
		const m = 0;
		for (const child of this._cursorSprite.children) {
			child.bitmap = this.menu_cursor_skin;
		}
		this._setRectPartsGeometry(this._cursorSprite, srect, drect, m);
	};
	//カーソルを微調整、あとカーソルを常に不透明に
	Window_SaveType.prototype._updateCursor = function () {
		this._cursorSprite.alpha = 255;
		this._cursorSprite.visible = this.isOpen() && this.cursorVisible;
		this._cursorSprite.x = this._cursorRect.x;
		this._cursorSprite.y = this._cursorRect.y - 4;
	};
	//未選択コマンドの背景を画像に
	Window_SaveType.prototype.drawItemBackground = function (index) {
		const rect = this.itemRect(index);
		if (this.menu_item_skin.isReady()) {
			const bitmap = this.menu_item_skin;
			const dx = rect.x;
			const dy = rect.y;
			const dw = rect.width;
			const dh = rect.height;
			this.contentsBack.blt(bitmap, 0, 0, 126, 58, dx, dy - 4, dw, dh);
		}
	};

	//カーソルが来た時、アイテムの文字名の色を変更する
	Window_SaveType.prototype.drawItem = function (index) {
		const rect = this.itemLineRect(index);
		const align = this.itemTextAlign();
		this.resetTextColor();

		var name = SceneManager._scene.constructor.name;
		var idx_now = 0;
		if (name == "Scene_Load") {
			idx_now = 1;
		}
		if (index == idx_now) {
			this.changeTextColor("#000000");
		} else {
			this.changeTextColor("#FFFFFF");
		}
		this.changePaintOpacity(this.isCommandEnabled(index));
		//文字をちょっと下にする
		this.drawTextS(this.commandName(index), rect.x, rect.y + 8, rect.width, align);
	};

	//セレクトするたびに背景をリフレッシュ
	// Window_SaveType.prototype.select = function (index) {
	// 	this._index = index;

	// 	this.contents.clear();
	// 	this.contentsBack.clear();
	// 	this.drawAllItems();

	// 	this.refreshCursor();
	// 	this.callUpdateHelp();
	// };
	//↑のセレクトでの不具合を出ないようにする
	Window_SaveType.prototype.drawAllItems = function () {
		this.contents.fontFace = "serif";
		const topIndex = this.topIndex();
		for (let i = 0; i < this.maxVisibleItems(); i++) {
			const index = topIndex + i;

			if (this._list && index < this.maxItems()) {
				//選択ちゅうだけ背景なくす
				if (i != this._index) {
					this.drawItemBackground(index);
				}
				this.drawItem(index);
			}
		}
	};

	Window_SaveType.prototype.playOkSound = function () {
		// SoundManager.playOk();
	};

	// #############################################################
	// ####################### 一覧ウィンドウ #######################
	// #############################################################
	Scene_File.prototype.listWindowRect = function () {
		const ww = 800;

		const wx = (1280 - ww) / 2;
		const wy = 50;
		const wh = 188 * 3 + 12 * 2;
		return new Rectangle(wx, wy, ww, wh);
	};

	//カーソルの変更
	Window_SavefileList.prototype.loadWindowskin = function () {
		this.windowskin = ImageManager.loadSystem("Window");
		this.menu_cursor_skin = ImageManager.loadSystem("menu_save_cursor");
		this.menu_item_skin = ImageManager.loadSystem("menu_save_item");
	};

	// //56×200にする
	Window_SavefileList.prototype._refreshCursor = function () {
		const drect = this._cursorRect.clone();
		const srect = { x: 0, y: 0, width: 800, height: 188 };
		const m = 0;
		for (const child of this._cursorSprite.children) {
			child.bitmap = this.menu_cursor_skin;
		}
		this._setRectPartsGeometry(this._cursorSprite, srect, drect, m);
	};

	// //未選択コマンドの背景を画像に
	Window_SavefileList.prototype.drawItemBackground = function (index) {
		const rect = this.itemRect(index);
		if (this.menu_item_skin) {
			const bitmap = this.menu_item_skin;
			const dx = rect.x;
			const dy = rect.y;
			const dw = rect.width;
			const dh = rect.height;
			this.contentsBack.blt(bitmap, 0, 0, 800, 188, dx, dy, dw, dh);
		}
	};
	Window_SavefileList.prototype.itemHeight = function () {
		return 188;
	};
	Window_SavefileList.prototype._refreshAllParts = function () {
		//this._refreshBack();
		//this._refreshFrame();
		this._refreshCursor();
		this._refreshArrows();
		this._refreshPauseSign();
	};

	Window_SavefileList.prototype.drawItem = function (index) {
		const savefileId = this.indexToSavefileId(index);
		const info = DataManager.savefileInfo(savefileId);
		const rect = this.itemRectWithPadding(index);
		this.resetTextColor();
		this.changePaintOpacity(this.isEnabled(savefileId));
		this.drawTitle(savefileId, rect.x - 10, rect.y + 74);
		if (info) {
			this.drawContents(info, rect);
		}
	};
	// ファイル名とかの描写、オートセーブいらないか？
	Window_SavefileList.prototype.drawTitle = function (savefileId, x, y) {
		this.contents.fontSize = 15;
		this.changeTextColor("rgba(0,0,0,1)");
		if (savefileId === 0) {
			this.drawTextM(TextManager.autosave, x, y, 180);
		} else {
			this.drawTextM(TextManager.file + " " + savefileId, x, y, 180);
		}
		this.resetFontSettings();
	};

	// 各要素の描写
	Window_SavefileList.prototype.drawContents = function (info, rect) {
		this.contents.fontSize = 17;
		this.changeTextColor("rgba(0,0,0,1)");

		var x1 = 370;
		var x2 = 470;
		var x3 = 490;
		var y1 = rect.y + 34;
		var line1 = 28;

		for (var i = 0; i < 4; i++) {
			this.drawTextS(["チャプタ―", "場所", "所持金", "プレイ時間"][i], x1, y1 + line1 * i, rect.width, "left");
			this.drawTextM(":", x2, y1 + line1 * i, rect.width, "left");
			this.drawTextS(
				[info.chapter, info.mapname || "不明", `${info.gold || 0} 円`, info.playtime][i],
				x3,
				y1 + line1 * i,
				Math.min(rect.width, 280),
				"left"
			);
		}
		let date = new Date(info.timestamp);
		this.drawTextS(
			`${date.getFullYear()}/${(date.getMonth() + 1).toString().padStart(2, "0")}/${date.getDate().toString().padStart(2, "0")}  ${date.getHours().toString().padStart(2, "0")}:${date.getMinutes().toString().padStart(2, "0")}`,
			578,
			rect.y + 2,
			rect.width,
			"left"
		);
		this.resetFontSettings();
		this.drawSnappedImage(info, rect);
	};

	// スクショの描写
	Window_SavefileList.prototype.drawSnappedImage = function (info, rect) {
		if (!info.snapUrl) {
			return;
		}
		const hasEncryptedImages = Utils.hasEncryptedImages();
		Utils._hasEncryptedImages = false;
		const bitmap = ImageManager.loadBitmapFromUrl(info.snapUrl);
		Utils._hasEncryptedImages = hasEncryptedImages;
		const dh = 140;
		const dw = 244;
		const dx = 98;
		const dy = rect.y + 22;
		this.changePaintOpacity(true);
		this.contents.blt(bitmap, 0, 0, bitmap.width, bitmap.height, dx, dy, dw, dh);
	};

	// ####################################################
	// ################# セーブ情報の追加 ##################
	// ####################################################
	Bitmap.prototype.toDataURL = function () {
		return this._canvas.toDataURL("image/png");
	};
	// 顔画像読み込ませない
	DataManager.loadAllSavefileImages = function () {
		for (const info of this._globalInfo.filter((x) => x)) {
			info.faces = [];
			this.loadSavefileImages(info);
		}
	};

	const DataManager_loadSavefileImages = DataManager.loadSavefileImages;
	DataManager.loadSavefileImages = function (info) {
		DataManager_loadSavefileImages.call(this, info);
		if (info.snapUrl) {
			const hasEncryptedImages = Utils.hasEncryptedImages();
			Utils._hasEncryptedImages = false;
			ImageManager.loadBitmap(info.snapUrl);
			Utils._hasEncryptedImages = hasEncryptedImages;
		}
	};

	const DataManager_makeSavefileInfo = DataManager.makeSavefileInfo;
	DataManager.makeSavefileInfo = function () {
		const info = DataManager_makeSavefileInfo.call(this);
		info.mapname = !!$dataMap ? $dataMapInfos[$gameMap.mapId()].name : "";
		info.gold = $gameParty._gold;
		info.chapter = $gameVariables.value(2);

		//セーブファイル画像の生成
		const bitmap = this.makeSavefileBitmap();
		if (bitmap) {
			info.snapUrl = bitmap.toDataURL();
		}

		return info;
	};
	DataManager.makeSavefileBitmap = function () {
		const bitmap = $gameTemp.getSavefileBitmap();
		if (!bitmap) {
			return null;
		}
		const scale = 0.15;
		const newBitmap = new Bitmap(bitmap.width * scale, bitmap.height * scale);
		newBitmap.blt(bitmap, 0, 0, bitmap.width, bitmap.height, 0, 0, newBitmap.width, newBitmap.height);
		return newBitmap;
	};

	const Game_Temp_initialize = Game_Temp.prototype.initialize;
	Game_Temp.prototype.initialize = function () {
		Game_Temp_initialize.call(this);
		this._savefileBitmap = null;
	};

	Game_Temp.prototype.setSavefileBitmap = function (bitmap) {
		this._savefileBitmap = bitmap;
	};
	Game_Temp.prototype.getSavefileBitmap = function () {
		if (this._savefileBitmap) {
			return this._savefileBitmap;
		} else {
			return SceneManager._backgroundBitmap;
		}
	};
})();
