//
// Mining module for TETDM 
// EditModule.java Version 0.36
// Copyright(C) 2011-2016 WATARU SUNAYAMA All RIGHTS RESERVED.
// This program is provided under the license.
// You Should read the README file.
//


package module.MiningModules.EditModule;

import source.*;
import source.TextData.*;


import java.io.*;
import java.nio.charset.Charset;
import java.util.*;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;


public class EditModule extends MiningModule implements ActionListener
{
//    JButton button[];
    int buttonNumber;
//	JToggleButton toggleButton[0];
	
    String editedText;
	String numberedText;

    String segment;
	
	String initialMessage;
	String savedText="";
	
	public EditModule()
	{
		setModuleID(1);
		setCategoryID(1);
		setUseMode(0);
		pairingVisualizationID = new int[]{1};
		setToolType(2);
        
        cancelPartialDocument = true;
	}

	public void initializePanel()
	{
		operationPanel.setBackground(Color.RED);

        buttonNumber = 7;
        
	    button = new JButton[buttonNumber];
	    toggleButton = new JToggleButton[1];

        operationPanel.setLayout(new GridLayout(2,4));
        
	    for(int i=0;i<buttonNumber;i++)
		{
		    button[i] = new JButton();
			button[i].setBackground(Color.red);
		    button[i].addActionListener(this);

		    operationPanel.add(button[i]);
		}
		
		toggleButton[0] = new JToggleButton();
		toggleButton[0].setBackground(Color.red);
		toggleButton[0].addActionListener(this);
		operationPanel.add(toggleButton[0]);		
		
	}	
	
	public void initializeData()
    {		
		String buttonNamesInEnglish[] = {"save+exec","saved text","add segment","add period","SEN->SEG","SEG->SEN","tag cut","line number"};

		if(isMenuInJapanese())
		{
			for(int i=0;i<buttonNumber;i++)
				button[i].setText(inJapanese[i]);
            
			toggleButton[0].setText(inJapanese[7]);
			segment = inJapanese[8];
			
			initialMessage = inJapanese[9];
		}
		else
		{
			for(int i=0;i<buttonNumber;i++)
				button[i].setText(buttonNamesInEnglish[i]);
            
			toggleButton[0].setText(buttonNamesInEnglish[7]);
			segment = "SEGMENT";
			
			initialMessage = "Please CUT & PASTE a document in this area, and PUSH ''save+exec'' button.";
		}
		savedText = text.originalText;
    }
	
	void makeNumberedText()
	{
        String kaigyo = System.getProperty("line.separator");        
        
		StringWriter sw = new StringWriter();			//For words
		BufferedWriter bw = new BufferedWriter(sw);	
		
		try{
			for(int i=0;i<text.segmentNumber;i++)
			{
				bw.write("<"+segment+" : "+(i+1)+">");
				bw.newLine();
				for(int j=0;j<text.segment[i].sentenceNumber;j++)
				{
					bw.write((text.segment[i].sentence[j].positionOfSentenceInText+1)+": ");
					for(int k=0;k<text.segment[i].sentence[j].wordNumber;k++)
						if(!text.segment[i].sentence[j].word[k].equals(kaigyo))
							bw.write(text.segment[i].sentence[j].word[k]);
					bw.newLine();
				}
			}
			bw.flush();
		}
		catch(Exception e){
			System.out.println("writing ERROR in EditModule");
		}		

		numberedText = sw.toString();
	}
    
	String tagCut()
	{        
		StringWriter sw = new StringWriter();			//For words
		BufferedWriter bw = new BufferedWriter(sw);
		
		try{
			for(int i=0;i<text.segmentNumber;i++)
				for(int j=0;j<text.segment[i].sentenceNumber;j++)
					for(int k=0;k<text.segment[i].sentence[j].wordNumber;k++)
						bw.write(text.segment[i].sentence[j].word[k]);
            
			bw.flush();
		}
		catch(Exception e){
			System.out.println("writing ERROR in EditModule");
		}
        
		return sw.toString();
	}
	
	String sentenceToSegment()
	{
        String kaigyo = System.getProperty("line.separator");		
		
		StringWriter sw = new StringWriter();			//For words
		BufferedWriter bw = new BufferedWriter(sw);

		try{
			for(int i=0;i<text.segmentNumber;i++)
				for(int j=0;j<text.segment[i].sentenceNumber;j++)
				{
					for(int k=0;k<text.segment[i].sentence[j].wordNumber;k++)
						bw.write(text.segment[i].sentence[j].word[k]);
					if(j != text.segment[i].sentenceNumber-1)
					{
						bw.write(kaigyo);
						bw.write(text.control.sp1.segment_tag);
						bw.write(kaigyo);
					}
				}
            
			bw.flush();
		}
		catch(Exception e){
			System.out.println("writing ERROR in EditModule");
		}
        
		return sw.toString();
	}	
	
	String segmentToSentence()
	{
        String kaigyo = System.getProperty("line.separator");		
		
		StringWriter sw = new StringWriter();			//For words
		BufferedWriter bw = new BufferedWriter(sw);
		
//		System.out.println("START CHECK!!");
		
		try{
			for(int i=0;i<text.segmentNumber;i++)
				for(int j=0;j<text.segment[i].sentenceNumber;j++)
				{
					for(int k=0;k<text.segment[i].sentence[j].wordNumber;k++)
						bw.write(text.segment[i].sentence[j].word[k]);
					if(j == text.segment[i].sentenceNumber-1)
					{
						int t;
						String checkWord = text.segment[i].sentence[j].word[text.segment[i].sentence[j].wordNumber-1];
						if(checkWord.equals(kaigyo) && text.segment[i].sentence[j].wordNumber > 2)
							checkWord = text.segment[i].sentence[j].word[text.segment[i].sentence[j].wordNumber-2];
							
//						System.out.println(checkWord+" ->check");
						
						for(t=0;t<text.control.sp1.touns;t++)
							if(checkWord.equals(text.control.sp1.kind_touns[t]))
								break;
								
						if(t == text.control.sp1.touns)
							bw.write(text.control.sp1.kind_touns[0]);

//						bw.write(kaigyo);
					}
				}
            
			bw.flush();
		}
		catch(Exception e){
			System.out.println("writing ERROR in EditModule");
		}
        
		return sw.toString();
	}	
    

	String addPeriods()
	{
        String kaigyo = System.getProperty("line.separator");
        int kaigyoCount;        
        
		StringWriter sw = new StringWriter();			//For words
		BufferedWriter bw = new BufferedWriter(sw);
		
		try{
			for(int i=0;i<text.segmentNumber;i++)
            {
				for(int j=0;j<text.segment[i].sentenceNumber;j++)
                {
                    kaigyoCount = 0;
                    
					for(int k=0;k<text.segment[i].sentence[j].wordNumber;k++)
                    {
						if(text.segment[i].sentence[j].word[k].equals(kaigyo))
                        {
                            kaigyoCount++;
                            
                            if(k != text.segment[i].sentence[j].wordNumber-1)	//must be a period
								if(k != 0 && kaigyoCount == 1)
									bw.write(text.control.sp1.kind_touns[0]);
                        }
                        else
                            kaigyoCount = 0;
						bw.write(text.segment[i].sentence[j].word[k]);
//						bw.write("["+i+","+j+","+k+","+text.segment[i].sentence[j].word[k]+"]");//
                    }
                }
                if(i != text.segmentNumber -1)
                    bw.write(text.control.sp1.segment_tag);
            }


			bw.flush();
		}
		catch(Exception e){
			System.out.println("writing ERROR in EditModule");
		}
        
		return sw.toString();
	}
    
	String wordData()
	{
        String kaigyo = System.getProperty("line.separator");
        int kaigyoCount;
        
		StringWriter sw = new StringWriter();			//For words
		BufferedWriter bw = new BufferedWriter(sw);
		
		try{
			for(int i=0;i<text.segmentNumber;i++)
				for(int j=0;j<text.segment[i].sentenceNumber;j++)
					for(int k=0;k<text.segment[i].sentence[j].wordNumber;k++)
						bw.write("["+i+","+j+","+k+","+text.segment[i].sentence[j].word[k]+"]");
            
			bw.flush();
		}
		catch(Exception e){
			System.out.println("writing ERROR in EditModule");
		}
        
		return sw.toString();
	}    
    
    
	String divideSegments()
	{
        String kaigyo = System.getProperty("line.separator");
        int kaigyoCount=0;

		StringWriter sw = new StringWriter();			//For words
		BufferedWriter bw = new BufferedWriter(sw);
		
		try{
			for (int i = 0; i < text.segmentNumber; i++) {
				InputStream in = new ByteArrayInputStream(text.segment[i].segmentText.getBytes("utf-8"));
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(in, Charset.forName("UTF-8")));

				String line;

				boolean isBeginningSegment = true;
				boolean isBlankLineBlock = false;
				while ( (line = reader.readLine()) != null) {
					if(isBeginningSegment) {
						if(line.length() != 0) {
							bw.write(line);
							bw.newLine();
							isBeginningSegment = false;
						} else {
							bw.newLine();
						}
					} else {

						if (line.length() == 0 ) {
							isBlankLineBlock = true;
							kaigyoCount++;
						} else if (line.length() != 0 && isBlankLineBlock) {
							bw.write(text.control.sp1.segment_tag);
							for (int j = 0; j < kaigyoCount; j++) {
								bw.newLine();
							}
							bw.write(line);
							bw.newLine();
							isBlankLineBlock = false;
							kaigyoCount = 0;
						} else {
							bw.write(line);
							bw.newLine();
						}
					}
				}

				if(i != text.segmentNumber -1) {
					bw.write(text.control.sp1.segment_tag);
					bw.newLine();
				}
            }

            bw.flush();
		}




		catch(Exception e){
			System.out.println("writing ERROR in EditModule");
		}
        
		return sw.toString();
	}
	
	public void miningOperations(int optionNumber)
	{
		switch(optionNumber)
		{
			case 0:
                resetData();
				if(text.originalText.equals(""))
					setDataString(initialMessage);
				else
//                    setDataString(text.sourceFilename+":"+text.originalText);
                    setDataString(text.originalText);
				break;
				
			case 1:
//				text.fileLoad();
                resetData();				
				setDataString(savedText);
				displayOperations(0);				
				break;
               
            case 3:
                editedText = tagCut();
                resetData();                
				setDataString(editedText);
				displayOperations(0);
				break;
                
            case 4:
                editedText = addPeriods();
                resetData();               
				setDataString(editedText);
				displayOperations(0);
				break;
                
            case 5:
                editedText = divideSegments();
                resetData();                
				setDataString(editedText);
				displayOperations(0);
				break;
                
			case 6:
				editedText = sentenceToSegment();
                resetData();                
				setDataString(editedText);
				displayOperations(0);				
				break;
				
			case 7:
				editedText = segmentToSentence();
                resetData();                
				setDataString(editedText);
				displayOperations(0);				
				break;
				
			case 8:
                /* CSV input from 10th column data
                String csvData[];
                
                csvData = FILEIO.CsvFileRead(new File(myModulePath+"seeds.csv"),10);
                
                editedText="";
                for(int i=1;i<csvData.length;i++)
                {
                        editedText += csvData[i];
                        editedText += System.getProperty("line.separator");
                    
                        if(i < csvData.length-1)
                            editedText += text.control.sp1.segment_tag+System.getProperty("line.separator");
                }

                            resetData();
                            setDataString(editedText);

                 */
                 
                /* ORIGINAL BEGIN */
                makeNumberedText();
                resetData();               
				setDataString(numberedText);
                 /*  ORIGINAL END */
				displayOperations(0);
				break;
                
   
		}
	}
	
	//Action listener
	public void actionPerformed(ActionEvent e)
	{
		writeButtonLog(e);/////NEW LOG
		
		//save+exec
		if(e.getSource() == button[0])
        {
            text.control.btd2x.doClick();
            //botton_point();
            toggleButton[0].setSelected(false);
			displayOperations(1);	//save text and re-calculation in all modules
            savedText = text.originalText;
            
            StoryControl.nextSerif(10000101);
        }		
		
		//recall saved text
		if(e.getSource() == button[1])
        {
            text.control.btd2x.doClick();
            toggleButton[0].setSelected(false);
			miningOperations(1);
			displayOperations(1);	//save text and re-calculation in all modules
            
            StoryControl.nextSerif(10000102);
        }
        
		//void lines -> seg
		if(e.getSource() == button[2])
        {
            text.control.btd2x.doClick();
            toggleButton[0].setSelected(false);
			displayOperations(2);//save text
			reLoad();	//reload saved text		
			miningOperations(5);
			displayOperations(1);	//save text and re-calculation in all modules
            
            StoryControl.nextSerif(10000103);
        }
		
        //newline -> sen
		if(e.getSource() == button[3])
        {
            text.control.btd2x.doClick();
            toggleButton[0].setSelected(false);
			displayOperations(2);//save text
			reLoad();	//reload saved text
			miningOperations(4);	//calculation and create new text
			displayOperations(1);	//save text and re-calculation in all modules
            
            StoryControl.nextSerif(10000104);
        }		
		
		//SEN -> SEG
		if(e.getSource() == button[4])//SEN->SEG
        {
            text.control.btd2x.doClick();
            toggleButton[0].setSelected(false);			
			miningOperations(6);
			displayOperations(1);	//save text and re-calculation in all modules
            
            StoryControl.nextSerif(10000105);
		}

		//SEG -> SEN
		if(e.getSource() == button[5])//SEG->SEN
        {
            text.control.btd2x.doClick();
            toggleButton[0].setSelected(false);			
			miningOperations(7);		
			displayOperations(1);	//save text and re-calculation in all modules
            
            StoryControl.nextSerif(10000106);
		}
		
		//tag cut
		if(e.getSource() == button[6])
        {
            text.control.btd2x.doClick();
            toggleButton[0].setSelected(false);			
			miningOperations(3);
			displayOperations(1);	//save text and re-calculation in all modules
            
            StoryControl.nextSerif(10000107);
        }

		//lineNumber
		if(e.getSource() == toggleButton[0])
		{/*
			int mining[] = {0,11,11,1};
			int visual[] = {0,1,8,1};
			int size[] = {1,2,3,4};
			panelSetFromModule(mining, visual, size);
			*/
			
			if(toggleButton[0].isSelected())
            {
				miningOperations(8);
                StoryControl.nextSerif(10000108);
            }
			else
				displayOperations(100);
			 
		}
	}
}
