/*
 * Copyright (c) 2015, StrategyQuant - All rights reserved.
 *
 * Code in this file was made in a good faith that it is correct and does what it should. 
 * If you found a bug in this code OR you have an improvement suggestion OR you want to include 
 * your own code snippet into our standard library please contact us at:
 * http://tasks.strategyquant.com/projects/snippets/
 *
 * This code can be used only within StrategyQuant products. 
 * Every owner of valid (free, trial or commercial) license of any StrategyQuant product 
 * is allowed to freely use, copy, modify or make derivative work of this code without limitations,
 * to be used in all StrategyQuant products and share his/her modifications or derivative work 
 * with the StrategyQuant community.
 *  
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR 
 * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES 
 * OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *  
 */package com.strategyquant.extend.DatabankActions;

import java.util.ArrayList;

import javax.swing.JOptionPane;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.strategyquant.lib.app.MainApp;
import com.strategyquant.lib.computers.SQPortfolioComputer;
import com.strategyquant.lib.databank.Databank;
import com.strategyquant.lib.databank.DatabankAction;
import com.strategyquant.lib.databank.DatabanksRegistry;
import com.strategyquant.lib.language.L;
import com.strategyquant.lib.plugins.SQGlobalEventMsg;
import com.strategyquant.lib.plugins.SQGlobalEvents;
import com.strategyquant.lib.results.SQOrderList;
import com.strategyquant.lib.results.SQResult;
import com.strategyquant.lib.results.SQResultsGroup;
import com.strategyquant.lib.settings.SQConst;
import com.strategyquant.lib.settings.SQCoreConst;

public class PortfolioMerge extends DatabankAction {
	public static final Logger Log = LoggerFactory.getLogger("PortfolioMerge");
	public SQPortfolioComputer portfolioComputer = new SQPortfolioComputer();
	
	public PortfolioMerge() {
		setName("Portfolio:"+L.t("Merge to a single strategy"));
	}
	
	@Override
	public void execute(Databank databank) {
		int count = databank.getNumberOfSelectedResults();
		
		if(count != 1) {
        	JOptionPane.showMessageDialog(MainApp.getFrame(),
        			L.t("You have to select one portfolio record."),
        			L.t("Portfolio Merge error"),
        		    JOptionPane.ERROR_MESSAGE);
        	return;			
		}
		
		try {
			mergePortfolio(databank.getSelectedResults().get(0), "PortfolioMerge");
			
			SQGlobalEvents.getInstance().callChangeEvent(SQGlobalEventMsg.EAA_SELECT_DATABANK, SQCoreConst.EAA_DATABANK_SIMPLE_STR);

		} catch(Exception e) {
			Log.error("Exc.", e);
			
        	JOptionPane.showMessageDialog(MainApp.getFrame(),
        			L.t("An error has occurred while merging the portfolio.")+"\n"+
        			e.getMessage(),
        			L.t("Portfolio Merge error"),
        		    JOptionPane.ERROR_MESSAGE);
        	
        	return;		
		}
	}
	
	private void mergePortfolio(SQResultsGroup portfolio, String name) throws Exception {
		ArrayList<String> symbols = portfolio.getResultKeysList();
		if(symbols.size() == 1) {
			DatabanksRegistry.get(SQCoreConst.EAA_DATABANK_SIMPLE_STR).add(portfolio);
			return;
		}

		SQOrderList orders = portfolio.getOrdersForResultKey(SQConst.SYMBOL_PORTFOLIO);

		SQResult result = new SQResult(portfolio.getResult(SQConst.SYMBOL_PORTFOLIO).getSettings());
		result.setOrders(orders);

		SQResultsGroup singleStrategy = new SQResultsGroup();
		singleStrategy.setSymbolsTable(portfolio.getSymbolsTable());
		singleStrategy.setStrategy(portfolio.getStrategy());
		singleStrategy.addResult(SQConst.SYMBOL_PORTFOLIO, result);
		singleStrategy.set("StrategyName", name);
		singleStrategy.computeResultsStats();
		
        DatabanksRegistry.get(SQCoreConst.EAA_DATABANK_SIMPLE_STR).add(singleStrategy);
	}

	public String[] getAllowedDatabanks() {
		return new String[]{"*", SQCoreConst.EAA_DATABANK_SIMPLE_STR+','+SQCoreConst.MM_SIM_DATABANK};
	}
	
	@Override
	public String getProduct() {
		return SQCoreConst.PRODUCT_EAA;
	}
	
	@Override
	public int getPreferredPosition() {
		return 6;
	}
}