/*:
 * @plugindesc v.1.1.0 [MV|MZ] [Add-on] Adds a “Sell” command for items with skills in the inventory. Allows you to sell items in your inventory.
 * @author DKPlugins
 * @url https://dk-plugins.ru
 * @target MZ
 * @base DK_Item_Actions
 * @orderAfter DK_Item_Actions
 * @help

 ### Info about plugin ###
 Title: DK_Item_Throw_Action
 Author: DKPlugins
 Site: https://dk-plugins.ru
 Version: 1.1.0
 Release: 05.10.2024
 First release: 04.09.2023

 ###===========================================================================
 ## Requirements and dependencies
 ###===========================================================================
 Availability of working plugin DK_Item_Actions
 Download page: https://dk-plugins.ru/item-actions

 ###=========================================================================
 ## Compatibility
 ###=========================================================================
 RPG Maker MV: 1.5+
 RPG Maker MZ: 1.0+

 ###=========================================================================
 ## See also
 ###=========================================================================
 1. Mouse System (https://dk-plugins.ru/mouse-system/)
 Allows you to change the mouse cursor, activate events by clicking, hovering, etc.

 2. Picture Choices (https://dk-plugins.ru/picture-choices/)
 Allows to use a graphic buttons instead of the choice window.

 3. Pictures Glow (https://dk-plugins.ru/pictures-glow/)
 Allows highlighting pictures on mouse hover.

 4. Video Player (https://dk-plugins.ru/video-player/)
 Adds video to the title screen, credits, the layers on the map and other.

 5. Events Glow (https://dk-plugins.ru/events-glow/)
 Allows highlighting events on mouse hover.

 ###=========================================================================
 ## License and terms of use
 ###=========================================================================
 You can:
 -To use the plugin for your non-commercial projects
 -Change code of the plugin

 You cannot:
 -Delete or change any information about the plugin
 -Distribute the plugin and its modifications

 ## Commercial license ##
 Visit the page: https://dk-plugins.ru/commercial-license/

 ###===========================================================================
 ## Support
 ###===========================================================================
 Become a subscriber on boosty: https://boosty.to/dkplugins
 Become a subscriber on patreon: https://patreon.com/dkplugins
 Donate: https://dk-plugins.ru/donate



 * @param commandName
 * @text Command name
 * @desc Command name. Use %1 to display the price and %2 to display the currency unit.
 * @default Sell %1 %2

*/

/*:ru
 * @plugindesc v.1.1.0 [MV|MZ] [Дополнение] Добавляет команду "Продать" для предметов в инвентаре. Позволяет продавать предметы в вашем инвентаре.
 * @author DKPlugins
 * @url https://dk-plugins.ru
 * @target MZ
 * @base DK_Item_Actions
 * @orderAfter DK_Item_Actions
 * @help

 ### Информация о плагине ###
 Название: DK_Item_Throw_Action
 Автор: DKPlugins
 Сайт: https://dk-plugins.ru
 Контакты: https://dk-plugins.ru/contacts
 Версия: 1.1.0
 Релиз: 05.10.2024
 Первый релиз: 04.09.2023

 ###===========================================================================
 ## Требования и зависимости
 ###===========================================================================
 Наличие включенного плагина DK_Item_Actions
 Страница загрузки: https://dk-plugins.ru/item-actions

 ###=========================================================================
 ## Совместимость
 ###=========================================================================
 RPG Maker MV: 1.5+
 RPG Maker MZ: 1.0+

 ###=========================================================================
 ## Инструкции
 ###=========================================================================

 ###=========================================================================
 ## Смотрите также
 ###=========================================================================
 1. Система Мыши (https://dk-plugins.ru/mouse-system/)
 Позволяет изменять курсор мыши, активировать события нажатием, наведением и др.

 2. Выбор С Изображениями (https://dk-plugins.ru/picture-choices/)
 Позволяет использовать графические кнопки вместо окна выбора.

 3. Свечение Изображений (https://dk-plugins.ru/pictures-glow/)
 Позволяет подсвечивать изображения при наведении мыши.

 4. Видео плеер (https://dk-plugins.ru/video-player/)
 Добавляет видео перед титульным экраном, титры, слои на карте и другое.

 5. Свечение Событий (https://dk-plugins.ru/events-glow/)
 Позволяет подсвечивать события при наведении мыши.

 ###=========================================================================
 ## Лицензия и правила использования плагина
 ###=========================================================================
 Вы можете:
 -Использовать плагин в некоммерческих проектах
 -Изменять код плагина

 Вы не можете:
 -Удалять или изменять любую информацию о плагине
 -Распространять плагин и его модификации

 ## Коммерческая лицензия ##
 Посетите страницу: https://dk-plugins.ru/commercial-license/

 ###=========================================================================
 ## Поддержка
 ###=========================================================================
 Стать подписчиком на boosty: https://boosty.to/dkplugins
 Стать подписчиком на patreon: https://patreon.com/dkplugins
 Поддержать: https://dk-plugins.ru/donate



 * @param commandName
 * @text Название команды
 * @desc Название команды. Используйте %1 для отображения цены и %2 для отображения валюты.
 * @default Продать за %1 %2

*/

'use strict';

var Imported = Imported || {};
Imported['DK_Item_Sell_Action'] = '1.1.0';

if (!Imported['DK_Item_Actions']) {
    throw new Error('"DK_Item_Sell_Action" require "DK_Item_Actions" plugin!');
}

//===========================================================================
// initialize parameters
//===========================================================================

const ItemSellActionParams = (function() {

    function parse(string) {
        try {
            return JSON.parse(string, function(key, value) {
                if (typeof string === 'number' || typeof string === 'boolean') {
                    return string;
                }

                try {
                    if (Array.isArray(value)) {
                        return value.map(val => parse(val));
                    }

                    return parse(value);
                } catch (e) {
                    return value;
                }
            });
        } catch(e) {
            return string;
        }
    }

    const parameters = PluginManager.parameters('DK_Item_Sell_Action');

    return Object.entries(parameters).reduce((acc, [key, value]) => {
        acc[key] = parse(value);

        return acc;
    }, {});

})();

//===========================================================================
// Scene_Item
//===========================================================================

const ItemSellAction_Scene_Item_evalAction =
    Scene_Item.prototype.evalAction;
Scene_Item.prototype.evalAction = function(action) {
    if (action.symbol === 'sell') {
        const item = this.item();
        const price = item.price;
        const number = this.number();
        const totalGold = price * number;

        $gameParty.gainGold(totalGold);
        $gameParty.loseItem(item, number);
    }

    ItemSellAction_Scene_Item_evalAction.apply(this, arguments);
};

const ItemSellAction_Scene_Item_playActionSe =
    Scene_Item.prototype.playActionSe;
Scene_Item.prototype.playActionSe = function(action) {
    if (action.symbol === 'sell') {
        SoundManager.playShop();
    } else {
        ItemSellAction_Scene_Item_playActionSe.apply(this, arguments);
    }
};

//===========================================================================
// Window_ItemActions
//===========================================================================

const ItemSellAction_Window_ItemActions_addOriginalCommands =
    Window_ItemActions.prototype.addOriginalCommands;
Window_ItemActions.prototype.addOriginalCommands = function() {
    ItemSellAction_Window_ItemActions_addOriginalCommands.apply(this, arguments);

    this.addAction(
        ItemSellActionParams.commandName.format(this._item.price, TextManager.currencyUnit),
        {
            symbol: 'sell',
            categories: ['item', 'weapon', 'armor'],
            inputNumber: true,
        }
    );
};

const ItemSellAction_Window_ItemActions_isActionVisible =
    Window_ItemActions.prototype.isActionVisible;
Window_ItemActions.prototype.isActionVisible = function(action) {
    if (action.symbol === 'sell') {
        return this._item.price > 0;
    }

    return ItemSellAction_Window_ItemActions_isActionVisible.apply(this, arguments);
};

//===========================================================================
// Window_ItemNumber
//===========================================================================

const ItemSellAction_Window_ItemNumber_setup =
    Window_ItemNumber.prototype.setup;
Window_ItemNumber.prototype.setup = function(user, item, action, actor, max) {
    ItemSellAction_Window_ItemNumber_setup.apply(this, arguments);

    if (action.symbol === 'sell') {
        this._price = item.price / 2;
        this.refresh();
    }
};
