/* $Id: WebDavSyncViewTableFactory.java 217 2011-06-10 00:53:06Z ohura $ */
package webdav;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Stack;

import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;

import smart_gs.logical.Preference;

import webdav.table.PropFindModel;
import webdav.table.PropFindRenderer;
import webdav.table.PropFindSort;


public class WebDavSyncViewTableFactory {
	
    private final PropFindModel model = new PropFindModel();
//    private final TableSorter sorter = new TableSorter(model);
    private final JTable table;
    protected WebDavProcessor webDavProcessor;
    protected Stack stack = new Stack();
    protected String owner = "user";
    protected String lockToken;
    protected JButton openButton;
    protected String openPath;
    protected ArrayList checkOpenList = new ArrayList();
    
    public static final int INITIALIZE    = 0;
    public static final int DOWNLOAD_DONE = 100;
    public static final int UPLOAD_DONE   = 200;
    
    
    protected int event = INITIALIZE;

    public WebDavSyncViewTableFactory(PropFindInfo[] propFindInfos,Color backgroundColor,final JButton openButton){
    	// table  = new JTable(sorter);
    	this.openButton = openButton;
        table  = new JTable(model);
        // sorter.setTableHeader(table.getTableHeader());
        //table  = new JTable(model);
        //table.setAutoCreateRowSorter(true);

        table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                return super.getTableCellRendererComponent(table, value, false, false, row, column);
            }
        });
        //table.setRowSelectionAllowed(true);
        //table.setCellSelectionEnabled(true);
        table.setIntercellSpacing(new Dimension());
        //table.setRowMargin(0);
        table.setShowGrid(false);
        //table.setShowHorizontalLines(false);
        //table.setShowVerticalLines(false);


        TableColumn col = table.getColumnModel().getColumn(0);
        col.setMinWidth(0);
        col.setMaxWidth(0);
        col.setResizable(false);
        //table.removeColumn(col);
        col = table.getColumnModel().getColumn(1);
        col.setCellRenderer(new PropFindRenderer(table));
        col.setPreferredWidth(100);
        col = table.getColumnModel().getColumn(2);
        col.setPreferredWidth(300);
        
        InputMap im = table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
        KeyStroke tab    = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0);
        KeyStroke enter  = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
        KeyStroke stab   = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, InputEvent.SHIFT_MASK);
        KeyStroke senter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.SHIFT_DOWN_MASK);
        im.put(tab, im.get(enter));
        im.put(stab, im.get(senter));

        if(propFindInfos != null){
	        for(int i=0;i<propFindInfos.length;i++){
	            model.addPropFindList(propFindInfos[i]);
	        }
        }
        final Color orgColor = table.getSelectionBackground();
//        final Color tflColor = this.getBackground();
        final Color tflColor = backgroundColor;
        table.addFocusListener(new FocusListener() {
            public void focusGained(FocusEvent e) {
                table.setSelectionForeground(Color.WHITE);
                table.setSelectionBackground(orgColor);
            }
            public void focusLost(FocusEvent e) {
                table.setSelectionForeground(Color.BLACK);
                table.setSelectionBackground(tflColor);
            }
        });
        table.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent me) {
            	Point pt = me.getPoint();
               	int row = table.rowAtPoint(pt);
                String name = (String)model.getValueAt(row, 1);
                String size = (String)model.getValueAt(row, 3);
                if(me.getClickCount()==2) {
                	/*
                    int row = sorter.modelIndex(table.rowAtPoint(pt));
                    */
                    if(size.equals("")){
                    	model.clear();
                    	openButton.setEnabled(false);
                    	try{
                    		boolean upflg = false;
                            if(name.equals("..")){
                            	stack.pop();
//                            	stack.remove(0);
//                            	System.out.println("POP:" + stack.pop());
                            	name = "";
                            	upflg = true;
                            }
	                		String path = getPath((String)stack.peek());
	                        PropFindInfo[] propFindInfoChild = webDavProcessor.getPropFindInfo(path + name, 1);
        					if(!(stack.size() == 1 && upflg)){
	        					PropFindInfo propFindInfo = new PropFindInfo();
	        					propFindInfo.setDisplayname("..");
	        					propFindInfo.setDirectory(true);
	        					model.addPropFindList(propFindInfo);
        					}
	        				if(propFindInfoChild != null){
	        					propFindInfoChild = new PropFindSort().sort(propFindInfoChild);
	        					for(int i=0;i<propFindInfoChild.length;i++){
	        						model.addPropFindList(propFindInfoChild[i]);
	        					}
	        				}
	        				if(!upflg){
	        					stack.push(path + name);
	        				}
						} catch (IOException e) {
							e.printStackTrace();
						}
					}else{
                		String path = getPath((String)stack.peek());
                		if(!name.equals("..")){
                        	cehckEnabled(path,name);
                		}else{
            			    openButton.setEnabled(false);
                		}
					}
                }else{
                    if(size.equals("")){
                		String path = getPath((String)stack.peek());
                		if(!name.equals("..")){
                			cehckEnabled(path,name);
                		}else{
            			    openButton.setEnabled(false);
                		}
                    }
                }
            }
        });
        table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent e) {
                if(e.getValueIsAdjusting()){
                	return;
                }
                int row = table.getSelectedRow();
				if(row == -1){
					return;
				}
				String name = (String)model.getValueAt(row, 1);
				String size = (String)model.getValueAt(row, 3);
                if(size.equals("")){
                	String path = (String)stack.peek();
                	cehckEnabled(path,name);
                }
			}
        });
        stack.push("");
    }
    public void cehckEnabled(String path ,String name){
    	try{
            
			PropFindInfo[] propFindInfoChild = webDavProcessor.getPropFindInfo(path + name, 1);
			if(propFindInfoChild != null){
				propFindInfoChild = new PropFindSort().sort(propFindInfoChild);
				boolean open = true;
				int matchcount = 0;
				for(int i=0;i<propFindInfoChild.length;i++){
					String displayname = propFindInfoChild[i].getDisplayname();
					boolean match = false;
					for(int j=0;j<checkOpenList.size();j++){
						String checkpath = (String)checkOpenList.get(j);
						File file = new File(checkpath);
						String checkname = file.getName();
						if(displayname.toLowerCase().equals(checkname)){
							match = true;
						}
					}
					if(match){
						matchcount++;
					}
				}
				if(checkOpenList.size() != matchcount){
					open = false;
				}
				if(open){
					this.openPath = path + name;
				}else{
					this.openPath = null;
				}
			    openButton.setEnabled(open);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    public void setCheckOpenList(ArrayList checkOpenList){
    	this.checkOpenList = checkOpenList;
    	
    }
    public void sync(){
		WebDavSyncData webDavSyncData = new WebDavSyncData();
		Preference preference = Preference.getInstance();
		for(int i=0;i<checkOpenList.size();i++){
			if(!webDavSyncData.init()){
				if(webDavProcessor == null){
		        	JOptionPane.showMessageDialog(
							new JFrame() , "It failed in login to WebDAV" , "fatal" ,
							JOptionPane.ERROR_MESSAGE
						);
		        	return;
				}
			}
			String path = (String)checkOpenList.get(i);
			File file = new File(path);
			String root = file.getAbsolutePath();
			root = root.substring(0,root.lastIndexOf(file.getName()));
			webDavSyncData.local(path,root);
			webDavSyncData.webdav(openPath,file.getName());
			webDavSyncData.sync(new File(root));
		}
		webDavSyncData.syncstart();
    }
    
    public void setWebDavProcessor(WebDavProcessor webDavProcessor){
    	this.webDavProcessor = webDavProcessor;
    }
    public JTable getJTable(){
    	return table;
    }
	public void setStack(Stack stack){
		this.stack = stack;
	}
	public String getPath(String path_){
		String path = path_;
		if(path == null){
			path = "";
		}
		if(!path.equals("")){
			if(!path.equals("/")){
				if(!path.endsWith("/")){
					path+="/";
				}
			}else{
				path = "";
			}
			if(path.startsWith("/")){
				path = path.substring(1,path.length());
			}
		}
		return path;
	}

}
