/*
   Tamot --- Task Modelling Editor
   Copyright (C) 2000 Commonwealth Scientific and Industrial Research Organisation
   (CSIRO), Australia. All rights reserved. 

   The Software, owned by CSIRO Australia, has been developed by the CSIRO 
   Intelligent Interactive Technology group. 
   For more information, please see http://www.cmis.csiro.au/iit/.

   The Software is a beta-test version for internal research and evaluation purposes 
   by the Licensee. The Software is still at a development stage. 
   It has not undergone complete testing and may have inherent errors,
   bugs or deficiencies that can affect the operation of the Software. 

   We encourage your feedback and suggestions. Any bugs / suggestions found please email to
   Shijian.Lu@cmis.csiro.au and Thomas.Lo@cmis.csiro.au. 

   After you have signed the Beta-Test Software License Agreement with the CSIRO,
   CSIRO grants you a non-exclusive, non-transferable license to use it only for your 
   personal, non-commercial and lawful end use. Implied licenses are negated. 

   Warranty Disclaimer : 

   CSIRO supplies the Software on an "as is" basis and makes no warranties that use of
   the Software by the Licensee will not infringe any third party’s 
   Intellectual Property Rights nor that the Software will be of merchantable quality,
   or suitable for a particular purpose. CSIRO excludes all terms, conditions and
   warranties implied by custom, the general law or statute in relation to the
   Software.
*/

package taskModellingTool;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.reflect.*;
import java.util.*;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.FileNotFoundException;

public class HTMLReportSettingDialog {

    private static final int MARGINX=50;
    private static final int SIZEX1=85;   // size of label
    private static final int GAPX=5;      // gap between label & checkbox
    private static final int SIZEX2=100;  // size of checkbox

    private static final int MARGINY=5;
    private static final int GAPY=5;
    

    private static final int SIZEXOK=60;
    private static final int SIZEXCANCEL=80;
    private static final int SIZEY=20;
    
    static final String SETTING_FILE="cfg"+File.separator+"setting.cfg";

    private static final Color BACKGROUND_COLOR=null;//Color.white;
    //private static final Color BACKGROUND_COLOR=new Color(255,255,255);
    private static final String TITLE ="Tick those attributes to appear in report";

    private GenericComponent currentClass=null;
    
    private boolean abort=false;
    
    private boolean modifyItself=true;
    
    private String oldName=null;
    
    protected JComponent [] jComp;
    
    protected String [] tMapkeys;
           
    public HTMLReportSettingDialog(TreeMap tMap) {       
    	String [] options={"OK","Cancel"};
        
    	int n=JOptionPane.showOptionDialog(MainFrame.mainFrame,createPanel(tMap),
    				TITLE,JOptionPane.OK_CANCEL_OPTION,
    				JOptionPane.PLAIN_MESSAGE,null,
    				options,options[0]);

    	if (n == JOptionPane.OK_OPTION) {
    		performModification();
    		saveHTMLReportSettings();
    	}
    }
    
    // save settings chosen into a file
    private void saveHTMLReportSettings() {
    	try {
   	    	BufferedWriter fileOut = new BufferedWriter(new FileWriter(SETTING_FILE));            
	
   	    	for (int i=0; i<tMapkeys.length; i++) {
   	    		Boolean b = new Boolean(((AbstractButton)jComp[i]).isSelected());
   	    	
   	    		String ss = tMapkeys[i]+" : "+b.toString();
   	    	
            	//System.out.println(ss);
            	fileOut.write(ss,0,ss.length());
            	fileOut.newLine();
   	    	}
   	    
   	    	fileOut.close();
    	}
    	catch (Exception e) {
    		String err = e.toString();
    		System.out.println(err);
    	}
    }
    
    // read settings from file
    public static void readHTMLReportSettings() {
    	String ss;
    	Boolean BF = new Boolean(false);
    	Boolean BT = new Boolean(true);
    	
    	try {
    		// if file exists ???
	        Manager.filedsKeyForHTML.clear();
   	    	BufferedReader fileIn = new BufferedReader(new FileReader(SETTING_FILE));            
	
    	    while ((ss = fileIn.readLine()) != null){
    	    	//System.out.println(ss);
    	    	
    	    	int i = ss.indexOf(" : ");
    	    	
    	    	String tmpField = ss.substring(0,i);
    	    	
    	    	Boolean b;
    	    	String tmpValue = ss.substring(i+3,ss.length()).toLowerCase();
    	    	if (tmpValue.charAt(0) == 't') b = BT;
    	    	else b = BF;
    	    	
    	    	//System.out.println("       ["+tmpField+"] ["+b+"]");
    	    	
                if (checkIfIncludedInHTMLReportSettings(tmpField)) {
                    Manager.taskAttributesBool.put(tmpField,b);

                    if (b.booleanValue())
                        Manager.filedsKeyForHTML.put(tmpField,Manager.filedsKey.get(tmpField));
                }
   	    	}
   	    
   	    	fileIn.close();
    	}
    	catch (FileNotFoundException e) {
    		System.out.println("The system cannot find the file ("+SETTING_FILE+").");
    	}
    	catch (Exception e) {
    		String err = e.toString();
    		System.out.println("error in reading HTML setting file: "+err);
    	}
    }
    
    public static boolean checkIfIncludedInHTMLReportSettings(String fieldName) {
        boolean result = false;
        
        if (fieldName.equals("semantics")) result = true;
        if (fieldName.equals("composite")) result = true;
        if (fieldName.equals("mandatory")) result = true;
        if (fieldName.equals("style")) result = true;
        if (fieldName.equals("minCard")) result = true;
        if (fieldName.equals("maxCard")) result = true;
        if (fieldName.equals("precondition")) result = true;
        if (fieldName.equals("feedback")) result = true;
        if (fieldName.equals("terminal")) result = true;
        if (fieldName.equals("dirty")) result = true;

        if (fieldName.equals("background")) result = true;
        if (fieldName.equals("comment")) result = true;
        if (fieldName.equals("tip")) result = true;
        if (fieldName.equals("warning")) result = true;
        if (fieldName.equals("annotation")) result = true;
        //System.out.println("fieldName = "+fieldName+" : "+result);
        
        return result;
    }
    
    private void performModification() {
        Boolean b;
        
        Manager.filedsKeyForHTML.clear();

        for (int i=0;i<tMapkeys.length;i++) {
   	    	b = new Boolean(((AbstractButton)jComp[i]).isSelected()); 
   	        
            try {
   	            Manager.taskAttributesBool.put(tMapkeys[i],b);
   	        } 
            catch (Exception except) {
            }

            if (b.booleanValue()) {
            	Manager.filedsKeyForHTML.put(tMapkeys[i],Manager.filedsKey.get(tMapkeys[i]));
            }
        }
    }
    
    private JPanel createPanel(TreeMap tMap) {
    	JPanel panel = new JPanel();
        panel.setBackground(BACKGROUND_COLOR);
        panel.setFont(new Font("Helvetica", Font.PLAIN, 14));        
    	panel.setLayout(null);
        
    	if (tMap!=null) {
    	    //Class cl=gc.getClass();
    	    //Object [] obj=gc.getDialogsFields();
    	    jComp = new JComponent[tMap.size()];
    	    tMapkeys = new String[tMap.size()];
    	    //fields=new Field[obj.length];
    	    JComponent jc;
    	    String key;
    	    //Field field;
    	    int posx=MARGINX;
    	    int posy=MARGINY;
    	    	
    	    panel.setPreferredSize(new Dimension(MARGINX+SIZEX1+GAPX+SIZEX2,MARGINY+(SIZEY+GAPY)*(tMap.size()+1)));
	    
            int counter=0;     
            //for (Enumeration e = tMap.keySet()  ; e.hasMoreElements() ;) 
        	for (Iterator i=tMap.keySet().iterator();i.hasNext();) {
        		key = (String)i.next();
            	tMapkeys[counter] =  key;
              	//System.out.println(e.nextElement());   		   
              
               	//Label
    		    jc = new JLabel(key);
    		    jc.setBounds(posx,posy,SIZEX1,SIZEY);
    		    posx += SIZEX1+GAPX;
                panel.add(jc);
                    
                //Value
                boolean b =((Boolean)tMap.get(key)).booleanValue() ;
             
                JCheckBox jch = new JCheckBox("",b); 		    
    		    jch.setBounds(posx,posy,SIZEX2,SIZEY);
    		    posx = MARGINX;
    		    posy += SIZEY+GAPY;
                jComp[counter] = jch;
    		    panel.add(jch);

                counter++;
            }
        
    	}
        return panel;
    }
}
