/*
 * 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.OverviewTab;

import java.util.ArrayList;

import com.strategyquant.lib.language.L;
import com.strategyquant.lib.results.SQResult;
import com.strategyquant.lib.results.SQResultsGroup;
import com.strategyquant.lib.results.SQStats;
import com.strategyquant.lib.results.StatsTypeCombination;
import com.strategyquant.lib.settings.SQConst;
import com.strategyquant.lib.utils.SQUtils;

public class SQDefaultWithPortfolio extends SQDefault {
	
	public SQDefaultWithPortfolio() {
		setName(L.t("SQ with Portfolio"));
		setScreenshotName("sqdefault_screenshot_portfolio.jpg");
		setHtmlTemplateName("sqdefault_template.htm");
	}
	
	@Override
	public String drawValues(SQResultsGroup strategyResult, String symbol, StatsTypeCombination combination) throws Exception {
		template = loadTemplate(); 
		replaceValues(strategyResult, symbol, combination);
		
		return template;
	}

	public void replaceValues(SQResultsGroup strategyResult, String symbol, StatsTypeCombination combination) {
		addPortfolioTable(strategyResult, symbol, combination);
		
		super.replaceValues(strategyResult, symbol, combination);
	}
		
	private void addPortfolioTable(SQResultsGroup strategyResult, String symbol, StatsTypeCombination combination) {
		if(strategyResult == null || !strategyResult.isPortfolio()) {
			return;
		}
		
		// add new style
		String style = "table.portfolio { width: 100%; background-color: #e0e2e3; color: #606060}\n"+
						"table.portfolio td { padding: 5px 5px 5px 10px; text-align: right; background-color: white; height: 15px; font-size: 11px;}\n"+
						"table.portfolio th { padding: 5px 5px 5px 10px; text-align: center; background-color: #eeeeee; font-size: 11px;}\n"+
						"table.portfolio td.name {white-space: nowrap;}";
		
		template = template.replace("</style>", style+"\n</style>");

		String portfolioPerformance = "<div class=\"performance\">"+
										"<h1>Symbols/Strategies in Portfolio</h1>"+
										"<table class=\"portfolio\" cellspacing=\"1\" cellpadding=\"0\" border=\"0\">"+
										"<tr>"+
										"<th>Name</th><th>Net Profit</th><th>Drawdown ($)</th><th>Drawdown (%)</th><th>Trades</th><th>Profit Factor</th><th>Sharpe Ratio</th><th>Return / DD Ratio</th><th>Avg. Trade</th>"+
										"</tr>"+
										printPortfolioListBody(strategyResult, combination)+
										"</table>"+
										"</div>"+
										"<br/><br/><br/>";

		template = template.replace("<div id=\"summaryBox\">", portfolioPerformance+"\n\n<div id=\"summaryBox\">");
	}

	private String printPortfolioListBody(SQResultsGroup strategyResult, StatsTypeCombination combination) {
		String tableBody = "";
		ArrayList<String> resultKeys = strategyResult.getResultKeysList();
		
		String plType = combination.getPLType();
		
		for(String resultKey : resultKeys) {
			SQResult result = strategyResult.getResult(resultKey);
			SQStats stats = result.getStats(SQConst.DIRECTION_ALL, plType, SQConst.KEY_SAMPLE_ALL);
			
			if(resultKey.equals(SQConst.SYMBOL_PORTFOLIO)) continue;
			
			tableBody += "<tr>"+
					"<td class=\"name\">"+limitStrategyName(resultKey)+"</td>"+
					"<td class=\"name\">"+SQUtils.d2WithPlType(stats.getDouble("NetProfit"),plType)+"</td>" + 
					"<td>$ "+stats.getDouble("Drawdown")+"</td>"+
					"<td>"+stats.getDouble("PctDrawdown")+" %</td>"+
					"<td>"+stats.getInt("NumberOfTrades")+"</td>"+
					"<td>"+stats.getDouble("ProfitFactor")+"</td>"+
					"<td>"+stats.getDouble("SharpeRatio")+"</td>"+
					"<td>"+stats.getDouble("ReturnDDRatio")+"</td>"+
					"<td class=\"name\">"+SQUtils.d2WithPlType(stats.getDouble("AvgTrade"), plType)+"</td>"+
					"</tr>";
		}
		
		// add portfolio result to the end
		SQResult result = strategyResult.getResult(SQConst.SYMBOL_PORTFOLIO);
		SQStats statsInMoney = result.getStats(SQConst.DIRECTION_ALL, plType, SQConst.KEY_SAMPLE_ALL);

		tableBody += "<tr>"+
				"<td class=\"name\"><strong>Portfolio</strong></td>"+
				"<td class=\"name\">"+SQUtils.d2WithPlType(statsInMoney.getDouble("NetProfit"), plType)+"</td>" + 
				"<td>$ "+statsInMoney.getDouble("Drawdown")+"</td>"+
				"<td>"+statsInMoney.getDouble("PctDrawdown")+" %</td>"+
				"<td>"+statsInMoney.getDouble("NumberOfTrades")+"</td>"+
				"<td>"+statsInMoney.getDouble("ProfitFactor")+"</td>"+
				"<td>"+statsInMoney.getDouble("SharpeRatio")+"</td>"+
				"<td>"+statsInMoney.getDouble("ReturnDDRatio")+"</td>"+
				"<td class=\"name\">"+SQUtils.d2WithPlType(statsInMoney.getDouble("AvgTrade"), plType)+"</td>"+
				"</tr>";
		
		return tableBody;
	}

	private String limitStrategyName(String resultKey) {
		if(resultKey.length() > 30) {
			return resultKey.substring(0, 30)+"...";
		}
		
		return resultKey;
	}

}
