/*
 * Licensed Materials - Property of Perforce Software, Inc. 
 * © Copyright Perforce Software, Inc. 2014, 2021 
 * © Copyright IBM Corp. 2009, 2014
 * © Copyright ILOG 1996, 2009
 * All Rights Reserved.
 *
 * Note to U.S. Government Users Restricted Rights:
 * The Software and Documentation were developed at private expense and
 * are "Commercial Items" as that term is defined at 48 CFR 2.101,
 * consisting of "Commercial Computer Software" and
 * "Commercial Computer Software Documentation", as such terms are
 * used in 48 CFR 12.212 or 48 CFR 227.7202-1 through 227.7202-4,
 * as applicable.
 */

package thinstock.faces.bean;

import java.util.Calendar;
import java.util.Date;
import java.util.StringTokenizer;

import javax.faces.context.FacesContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import ilog.views.chart.faces.dhtml.component.IlvChartDHTMLView;
import ilog.views.util.IlvLocaleUtil;
import ilog.views.util.IlvResourceUtil;
import ilog.views.util.time.IlvCalendarFactory;
import thinstock.StockDemo;
import thinstock.StockDemoApp;
import thinstock.faces.component.MinorChartView;

public class StockBean {

  private String lower1Indicator = "0";

  private String lower2Indicator = "1";

  private String[] upperIndicators = new String[0];

  private String symbol = "";

  private String secSymbols = "";
  
  private String apiKey = "";

  private String frequency = "0";

  private String duration = "4";

  private IlvChartDHTMLView chartView = new IlvChartDHTMLView();

  private MinorChartView lower1 = new MinorChartView();

  private MinorChartView lower2 = new MinorChartView();

  protected StockDemoApp getApp(HttpServletRequest request) throws ServletException {
    if (request != null) {
      StockDemoApp app = null;
      synchronized (request.getSession(true)) {
        // Use the page identifier to retrieve the StockDemoApp
        // in order to support multiple browser pages.
        app = (StockDemoApp) StockDemo.getSessionAttribute(request, StockDemo.APP_SESSION_KEY);
      }
      if (app != null)
        return app;
      else {
        String msg = IlvResourceUtil.getCurrentLocaleString(StockBean.class, "notRetriveAppFromSession");
        throw new ServletException(msg);
      }
    }
    String msg = IlvResourceUtil.getCurrentLocaleString(StockBean.class, "notRetriveAppFromSession");
    throw new ServletException(msg);
  }

  protected StockDemoApp getApp() throws ServletException {
    return getApp((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest());
  }

  public String loadQuotes() {
    Calendar c = IlvCalendarFactory.createInstance(IlvLocaleUtil.getCurrentULocale());
    Date to = c.getTime();

    switch ((Integer.valueOf(duration)).intValue()) {
    case 0:
      c.add(Calendar.MONTH, -1);
      break;
    case 1:
      c.add(Calendar.MONTH, -2);
      break;
    case 2:
      c.add(Calendar.MONTH, -3);
      break;
    case 3:
      c.add(Calendar.MONTH, -6);
      break;
    case 4:
      c.add(Calendar.YEAR, -1);
      break;
    case 5:
      c.add(Calendar.YEAR, -2);
      break;
    case 6:
      c.add(Calendar.YEAR, -3);
      break;
    case 7:
      c.add(Calendar.YEAR, -5);
      break;
    case 8:
      c.add(Calendar.YEAR, -10);
      break;
    default:
    }

    // Pass the API key down to the data source.
        try {
          getApp().setAPIKey(getApiKey());
        } catch (ServletException e) {
          e.printStackTrace();
        }

    Date from = c.getTime();
    loadQuotes(from, to);

    return "";
  }

  private void loadQuotes(Date from, Date to) {
    try {
      StockDemoApp demo = getApp();
      String lSym = symbol;
      String[] ss = extractSecSymbols();
      if (demo.loadQuotes(lSym, from, to, (Integer.valueOf(frequency)).intValue(), ss)) {
        demo.primaryDataLoaded(lSym, ss);
        chartView.setDefaultChartVisibleWindow();
      }
    } catch (ServletException e) {
      e.printStackTrace();
    }
  }

  protected String[] extractSecSymbols() {
    StringTokenizer stk = new StringTokenizer(getSecSymbols(), " ");
    String[] res = new String[stk.countTokens()];
    int i = 0;
    while (stk.hasMoreTokens()) {
      String token = stk.nextToken();
      if (token != null) {
        res[i++] = token;
      }
    }
    return res;
  }

  /**
   * @return Returns the lower1Indicator.
   */
  public String getLower1Indicator() {
    return lower1Indicator;
  }

  /**
   * @param lower1Indicator
   *          The lower1Indicator to set.
   */
  public void setLower1Indicator(String lower1Indicator) {
    this.lower1Indicator = lower1Indicator;
    setMinorIndicator(0, lower1Indicator);
  }

  /**
   * @return Returns the lower2Indicator.
   */
  public String getLower2Indicator() {
    return lower2Indicator;
  }

  /**
   * @param lower2Indicator
   *          The lower2Indicator to set.
   */
  public void setLower2Indicator(String lower2Indicator) {
    this.lower2Indicator = lower2Indicator;
    setMinorIndicator(1, lower2Indicator);
  }

  /**
   * @return Returns the upperIndicators.
   */
  public String[] getUpperIndicators() {
    return upperIndicators;
  }

  /**
   * @param upperIndicators
   *          The upperIndicators to set.
   */
  public void setUpperIndicators(String[] upperIndicators) {
    this.upperIndicators = upperIndicators;
    try {
      StockDemoApp demo = getApp();
      if (upperIndicators != null) {
        int[] upIndics = new int[upperIndicators.length];
        for (int i = 0; i < upperIndicators.length; i++)
          upIndics[i] = Integer.parseInt(upperIndicators[i]);

        demo.setUpperIndicators(upIndics);
      } else {
        demo.setUpperIndicators(new int[0]);
      }

    } catch (ServletException e) {
      e.printStackTrace();
    }

  }

  public void setMinorIndicator(int chartIdx, String indicator) {
    try {
      getApp().setLowerIndicator(chartIdx, Integer.parseInt(indicator));
    } catch (NumberFormatException e) {
      e.printStackTrace();
    } catch (ServletException e) {
      e.printStackTrace();
    }
  }

  /**
   * @return Returns the secSymbol.
   */
  public String getSecSymbols() {
    return secSymbols;
  }

  /**
   * @param secSymbol
   *          The secSymbol to set.
   */
  public void setSecSymbols(String secSymbols) {
    this.secSymbols = secSymbols;
  }

  /**
   * @return Returns the symbol.
   */
  public String getSymbol() {
    return symbol;
  }

  /**
   * @param symbol
   *          The symbol to set.
   */
  public void setSymbol(String symbol) {
    this.symbol = symbol;
  }

  /**
   * @return Returns the API key.
   */
 public String getApiKey() {
        return apiKey;  
  }
  
 /**
  * Sets the API key.
  * 
  * @param apiKey String
  */
  public void setApiKey(String apiKey) {
      this.apiKey = apiKey;
  }

  /**
   * @return Returns the duration.
   */
  public String getDuration() {
    return duration;
  }

  /**
   * @param duration
   *          The duration to set.
   */
  public void setDuration(String duration) {
    this.duration = duration;
  }

  /**
   * @return Returns the frequency.
   */
  public String getFrequency() {
    return frequency;
  }

  /**
   * @param frequency
   *          The frequency to set.
   */
  public void setFrequency(String frequency) {
    this.frequency = frequency;
  }

  /**
   * @return Returns the chartView.
   */
  public IlvChartDHTMLView getChartView() {
    return chartView;
  }

  /**
   * @param chartView
   *          The chartView to set.
   */
  public void setChartView(IlvChartDHTMLView chartView) {
    this.chartView = chartView;
  }

  public MinorChartView getLower1() {
    return lower1;
  }

  public void setLower1(MinorChartView lower1) {
    this.lower1 = lower1;
  }

  public MinorChartView getLower2() {
    return lower2;
  }

  public void setLower2(MinorChartView lower2) {
    this.lower2 = lower2;
  }

  public boolean isErrorOccured() {
    return FacesContext.getCurrentInstance().getMessages().hasNext();
  }
  
}