//
// Mining module for TETDM 
// Dictionary.java Version 1.02 //2012/3/1
// You should read the README file.
//

package module.MiningModules.Dictionary;

import source.*;
import source.TextData.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.net.URLDecoder;
import java.net.URL;
import java.util.regex.*;

import java.io.*;


public class Dictionary extends MiningModule implements ActionListener
{
	String searchResults;
    String result;
    String readResults;
	
	JTextField textfield;
    
    boolean searchEnglishWord = false;
    
    ButtonGroup buttonGroup;
    
    String logFilename;
    boolean searchFailure = false;

	public Dictionary()
	{
		setModuleID(21);						// Set your module ID after you have got it
		setCategoryID(8);
		setUseMode(1);
        pairingVisualizationID = new int[]{15};
        focusExecute = true;
	}

	public void initializePanel()
	{
		textfield = new JTextField(10);
		textfield.addActionListener(this);
		operationPanel.add(textfield);
		
        button = new JButton[1];
		button[0] = new JButton("List Clear");
		button[0].setBackground(Color.red);
		button[0].addActionListener(this);
		operationPanel.add(button[0]);
        
        toggleButton = new JToggleButton[2];
        
        toggleButton[0] = new JToggleButton("Japanese");
        toggleButton[0].setBackground(Color.red);
        toggleButton[0].addActionListener(this);
        operationPanel.add(toggleButton[0]);
        
        toggleButton[1] = new JToggleButton("English");
        toggleButton[1].setBackground(Color.red);
        toggleButton[1].addActionListener(this);
        operationPanel.add(toggleButton[1]);
		
		operationPanel.setBackground(Color.RED);
        
		if(isMenuInJapanese())
        {
            button[0].setText(inJapanese[4]);
            toggleButton[0].setText(inJapanese[8]);
            toggleButton[1].setText(inJapanese[9]);
        }
		
        buttonGroup = new ButtonGroup();
        buttonGroup.add(toggleButton[0]);
        buttonGroup.add(toggleButton[1]);

        if(searchEnglishWord)
            toggleButton[1].setSelected(true);
        else
            toggleButton[0].setSelected(true);
        
        searchResults = "";
        logFilename = myModulePath+"searchLog.txt";
        searchResults = fileRead(logFilename);
	}
	
	public void initializeData(){}
	
	public void miningOperations(int optionNumber)
	{		
		switch(optionNumber)
		{
			case 25:
				if(!textfield.getText().equals(""))
					setMainFocusString(textfield.getText());
			
			case 4500:	
			case 0: 
				if(!getMainFocusString().equals(""))
				{
					WordSearch(getMainFocusString());
					setDataString(1,searchResults);
					displayOperations(102);
					textfield.setText("");
                    
                    System.out.println("SEARCH WORD = "+getMainFocusString());
                    
                    if(searchFailure == false)
                    {
                        readResults = fileRead(logFilename);
                        //                    FILEIO.TextFileWriteCode2(new File(logFilename), searchResults, "SHIFT-JIS");
                        FILEIO.TextFileWriteCode(new File(logFilename), result+("\n\n")+readResults, "SHIFT-JIS");
                    }
				}
                else
                {
                    setDataString(1,searchResults);
                    displayOperations(102);
                }
                
				displayOperations(100);
                setMainFocusString("");
				break;			
		}
	}
	
	public void actionPerformed(ActionEvent e)
	{
		writeButtonLog(e);/////NEW LOG		
		
//		insideOfActionPerformed(e);		
		
		if(e.getSource() == button[0])		//list clear
		{
			searchResults = "";			
			setDataString(1,searchResults);
			displayOperations(100);
			displayOperations(103);
            
            int option;
            
            if(isMenuInJapanese())
               option = JOptionPane.showConfirmDialog(this, inJapanese[10], "OK", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
            else
                option = JOptionPane.showConfirmDialog(this, "ALSO REMOVE LOG FILE, OK?", "OK", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
            
            if(option != JOptionPane.YES_OPTION)
                return;
            
            FILEIO.TextFileWriteCode(new File(logFilename), "", "SHIFT-JIS");
		}
        
        if(e.getSource() == toggleButton[0])		//Japanese
        {
            if(toggleButton[0].isSelected())
                searchEnglishWord = false;
        }
        
        if(e.getSource() == toggleButton[1])		//English
        {
            if(toggleButton[1].isSelected())
                searchEnglishWord = true;
        }
		
		if(e.getSource () == textfield)
			miningOperations(25);		
	}
	
	//Word Search
	void WordSearch(String searchWord)
	{
		String failedText;
		String ss;
        
		result = "";
		
		failedText = "-"+searchWord+inJapanese[3];
        searchFailure = false;
        
        if(searchEnglishWord)
        {
            if((ss = GetQA(0,searchWord)) != null)	//yahoo
                result += ("-"+searchWord+"\n ["+ss+"...]\n---"+inJapanese[7]);
            else
            {
                if((ss = GetQA(1,searchWord)) != null)	//goo
                    result += ("-"+searchWord+"\n ["+ss+"...]\n----"+inJapanese[6]);
                else
                {
                    if((ss = GetQA(2,searchWord)) != null)	//Wiktionary
                        result += ("-"+searchWord+"\n ["+ss+"...]\n---"+inJapanese[2]);
                    else
                    {
                        result += failedText;
                        searchFailure = true;
                    }
                }
            }
        }
        else
        {
            if((ss = GetQA(0,searchWord)) != null)	//yahoo
                result += ("-"+searchWord+"\n ["+ss+"...]\n---"+inJapanese[0]);
            else
            {
                if((ss = GetQA(1,searchWord)) != null)	//goo
                    result += ("-"+searchWord+"\n ["+ss+"...]\n---"+inJapanese[1]);
                else
                {
                    if((ss = GetQA(2,searchWord)) != null)	//Wiktionary
                        result += ("-"+searchWord+"\n ["+ss+"...]\n---"+inJapanese[2]);
                    else
                    {
                        result += failedText;
                        searchFailure = true;
                    }
                }
            }
        }
		
		searchResults = result+("\n\n")+searchResults;
	}
	
	String GetQA(int p, String qWord)
	{
//        System.out.println("p="+p+" "+qWord);
        
		String path="";
		
		HttpURLConnection urlconn = null;
		BufferedReader br = null;
		try{
			long count_result;
			qWord = URLEncoder.encode(qWord , "UTF-8");
			
			if(p==0){
                if(searchEnglishWord)
                    path = "https://kotobank.jp/ejword/"+ qWord;		//yahoo
                else
                    path = "https://kotobank.jp/word/"+ qWord;			//yahoo
			}else if(p==1){
                if(searchEnglishWord)
                    path = "https://dictionary.goo.ne.jp/srch/en/"+qWord+"/m0u/";	//goo
                else
                    path = "https://dictionary.goo.ne.jp/srch/all/"+qWord+"/m0u/";	//goo
			}else if(p==2){
				path = "https://ja.wiktionary.org/wiki/"+ qWord;			//Wiktionary
			}	
			URL url = new URL(path);
			urlconn = (HttpURLConnection) url.openConnection();
			urlconn.connect();
			
			InputStreamReader ir = new InputStreamReader(urlconn.getInputStream(),getCharset(urlconn));
			br = new BufferedReader(ir);
			
			StringBuilder sb = new StringBuilder();
			String line;
			
			while((line=br.readLine())!=null)
				sb.append(line);
			
			String count = getHitCount(qWord, sb.toString(),p);
			if(count != null){
				//System.out.println("bf:"+count.length());
				count = count.replaceAll("<.+?>","");
				//System.out.println("af:"+count.length());
                
                System.out.println(count);
                
                if(count.length() > 300)
                    count = count.substring(0,300)+" ......";
//                else if(count.length() > 150)
  //                  count = count.substring(0,150)+" ...";
			}
			
			return count;
		
		}catch (MalformedURLException e){
//			System.out.println("MalformedURLException@GETQA@Dictionary_"+p);
//			e.printStackTrace();
			return null;
		}catch(IOException e1){
//			System.out.println("IOException@GETQA@Dictionary_"+p);
//			e1.printStackTrace();
			return null;
		}finally{
			try {
			if (br != null)
				br.close();
			}catch (IOException e){
//				System.out.println("finallyIOException@GETQA@Dictionary_"+p);
				//e.printStackTrace();
			}if(urlconn != null)
				urlconn.disconnect();
		}	
	}
	
	public String getHitCount(String qWord, String cont,int pp)
	{ 
		String preStr="",postStr="";
		
		if(pp==0){
			preStr = "\"description\" content=\"";		//hyakkajiten
			postStr = "/>";
			//postStr = inJapanese[5];		//1st sentence only
		}else if(pp==1){
			preStr = "mean text-b\">";
			postStr = "</dd>";		//goo
		}else if(pp==2){
			preStr = "<li>";
			//postStr = "</li>";
			postStr = inJapanese[5];			//Wiktionary
		}
		
		int preIndex = cont.indexOf(preStr);
		if (preIndex == -1)
			return null;
		int postIndex = cont.indexOf(postStr, preIndex);
		if (postIndex == -1)
			return null;
		return cont.substring(preIndex + preStr.length(), postIndex);
	}

	public String getCharset(HttpURLConnection urlconn)
	{
		String defaultCharset = "UTF-8";
		String cont = urlconn.getContentType();
		if (cont == null || !cont.contains("charset"))
			return defaultCharset;
		return cont.substring(cont.indexOf("=") + 1);
	}
	
	public String TagCut(String st){
		Pattern pattern = Pattern.compile("[\\s]+", Pattern.DOTALL);
		
		Matcher matcher = pattern.matcher(st);
		String cut_st = matcher.replaceAll("");
		
		return cut_st;
		
	}
}
