

//
// Core Program for TETDM 
// StoryControl.java Version 1.00
// Copyright(C) 2017-2018 TETDM CORE MEMBER ALL RIGHTS RESERVED.
// This program is provided under the license.
//


package source;

import source.*;
import source.GameMode.*;
import source.Tutorial.*;
import source.TextData.*;
import source.Utility.*;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.text.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.image.*;
import javax.imageio.ImageIO;

import java.awt.geom.RoundRectangle2D;

import static java.awt.BorderLayout.* ;

public class StoryControl extends JFrame ////////////////////////
{
    public static boolean constructorExecuted = false;
    
    //PANEL
    public static PopUpForStory popForStory[] = new PopUpForStory[8];   // NOT USE 0
    public static PopUpForChapter popForChapter[] = new PopUpForChapter[13];   // NOT USE 0
    
    public static PopUpForAssist popForAssist;
    public static PopUpForFunnel popForFunnel;
    public static PopUpForSerif popForSerif;
    public static PopUpForSquare popForSquare;
    public static PopUpForMoveCharacter popForMoveCharacter;
    
    static Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
    static int charaX = size.width-200;
    static int charaY = size.height-200;
    public static int FunnelX, FunnelY; /////////
    public static int SquareX,SquareY,SquareWidth,SquareHeight;
    
    public static PopUpForQuestion popForQuestion;
    
    public static ImagePanel image; //chapter0
    public static ImagePanel2 image2;   //display image (mining process)

    public static int SelectMode;       // For PausePanel : go back to chapterPanel

    //serif, operation
    public static String tutorialData[] = new String[1000];
    public static String serif[] = new String[500]; // MAX LINE Number for serif
    public static String operate[] = new String[500]; // 2 times of MAX Number for tag
  
    static int goVoiceNumber = 0;
    static int currentVoiceNumber = -1;
    static int backVoiceNumber = 0;

    public static int numberForAction;

    //Flags
    static int nextDisposeWindow = 0;          //for next dispose window
    public static int actionNumber = 0;     //for challenge
    public static int changeMiningNumber = 0;  //for settool
    public static int changeVisualizationNumber = 0;  //for settool
    public static String changeTextFilename = "";    //for settext
    
    
    //Initailize
    public static Control control;
    public static String mode;
    public static int modeNumber;
    public static int missionNumber;
    public static String serifPath;
    
    public static int subMissionNumber[] = new int[13];
    
    //ToolTutorial
    public static int maxModuleTutorial = 100;
    public static int moduleTutorialIndex[][] = new int[4][maxModuleTutorial];
    public static String moduleTutorialFilename[][] = new String[4][maxModuleTutorial];
    public static String moduleTutorialClearFilename[][] = new String[4][maxModuleTutorial];
    public static String moduleNameInJapanese[][] = new String[4][maxModuleTutorial];
    public static int moduleTutorialCount[] = new int[4];
    
    public static boolean fromModule = false;   //true: Activated by Module
    public static boolean voice = false;    //true: use sayCommand on Mac
    public static boolean clearFlag = false;    //true: No delay time to skip serif
    
    public StoryControl(Control control)
    {
        this.control = control;
        setSerifPath(control);
        
        constructorExecuted = true;
    }
    
    public StoryControl(Control control, String mode, int modeNumber, int missionNumber)
	{
        this.control = control;
        this.mode=mode;
        this.modeNumber=modeNumber;
        this.missionNumber=missionNumber;
        setSerifPath(control);
        
        constructorExecuted = true;
        
        goVoiceNumber = 0;
        currentVoiceNumber = -1;
        
        //FOR CLEARFLAG
        if(modeNumber % 3 == 1)
            clearFlag = clearFlagCheckOperation(missionNumber, modeNumber);
        if(modeNumber % 3 == 2)
            clearFlag = clearFlagCheckTool(missionNumber, modeNumber);
        if(modeNumber % 3 == 0)
            clearFlag = clearFlagCheckMining(missionNumber, modeNumber);
        
        writeTimeLog("START");
        

        readTutorialData2();
    }
    
    public static void createOperate(String operateLine, int operationCount, int serifCount, int serifTotalCount, boolean face)
    {
        if(operateLine.equals(""))
            operate[operationCount] = String.valueOf(serifCount);
        else if(face)
            operate[operationCount] = String.valueOf(serifCount) +":"+String.valueOf(serifTotalCount-1)+operateLine;
        else
            operate[operationCount] = String.valueOf(serifCount) + operateLine;
    }

    
    public static void readTutorialData2()
    {
        int tutorialDataNumber=0, serifCount, serifTotalCount, operationCount;

        try{
            File dataFile = new File(serifPath+mode+File.separator+missionNumber+".txt");
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(dataFile), "JISAutoDetect"));
            for(tutorialDataNumber=0;(tutorialData[tutorialDataNumber] = br.readLine()) != null;tutorialDataNumber++)
                ;
            br.close();
            
            if(mode.equals("SL") && missionNumber==1)
            {
                br = new BufferedReader(new FileReader(new File(serifPath+"coslog.txt")));
                String chara = br.readLine();
                br.close();
                
                String nameData[];
                nameData = FILEIO.TextFileAllReadCodeArray(new File(serifPath+mode+File.separator+"charname.txt"));
                
                tutorialData[1] = nameData[Integer.parseInt(chara)] + tutorialData[1];
            }
        }
        catch(FileNotFoundException e){
            System.out.println(e);
        }catch(IOException e){
            System.out.println(e);
        }

        serifCount = 0;
        serifTotalCount = 0;
        operationCount = 0;
        String splitTutorialData[];
        String operateLine = "";
        boolean face = false;
        String tag = "";
        
        for(int i=0;i<tutorialDataNumber;i++)
        {
            splitTutorialData = tutorialData[i].split(":");
            tag = splitTutorialData[0];

            if(i==0 && tutorialData[0].length() != 0)     // INITIAL LINE with serif or tag
                if(!(tag.equals("funnel")|| tag.equals("square")|| tag.equals("challenge")|| tag.equals("settool")|| tag.equals("settext")|| tag.equals("question")|| tag.equals("image")|| tag.equals("sound")|| tag.equals("face")))
                    operate[operationCount++] = "normal";
            
            if(tutorialData[i].length() == 0)   // VOID LINE
                tag = "normal";
            
            if(tag.equals("normal") || tag.equals("funnel") || tag.equals("square") || tag.equals("challenge")|| tag.equals("settool") || tag.equals("settext")|| tag.equals("image")||
               tag.equals("imagenextout")|| tag.equals("sound")|| tag.equals("face") || tag.equals("question") || tag.equals("end"))
            {
                if(i!=0)    //create operate for last tag
                    createOperate(operateLine, operationCount++, serifCount, serifTotalCount, face);
                face = false;
                operateLine = "";
                
                operate[operationCount++] = tag;
            }
            
            
            if(tag.equals("normal"))
            {
                serifCount = 0;
                continue;
            }
            
            if(tag.equals("end"))
            {
                serifCount = Integer.parseInt(splitTutorialData[1]);
                continue;
            }
            
            if(tag.equals("settext")|| tag.equals("image")|| tag.equals("imagenextout")|| tag.equals("sound")|| tag.equals("face"))
            {
                operateLine = ":"+splitTutorialData[1];
                serifCount = 0;
                
                if(tag.equals("face"))
                    face = true;
                
                continue;
            }
            
            if(tag.equals("funnel") || tag.equals("square") || tag.equals("challenge"))
            {
                if(splitTutorialData.length == 2)
                    operateLine = ":"+splitTutorialData[1]+":0";
                else
                    operateLine = ":"+splitTutorialData[1]+":"+splitTutorialData[2];
                serifCount = 0;
                
                continue;
            }
            
            if(tag.equals("settool"))
            {
                operateLine = ":"+splitTutorialData[1]+":"+splitTutorialData[2];
                serifCount = 0;
                
                continue;
            }

            if(tag.equals("question"))
            {
                operateLine = "";
                for(int j=1;j<=5;j++)
                    operateLine += ":"+splitTutorialData[j];
                
                int smileNumber=operationCount/2, sadNumber=operationCount/2;
                
                int j;
                for(j=i+1;j<tutorialDataNumber;j++)
                {
                    splitTutorialData = tutorialData[j].split(":");
                    String tag2 = splitTutorialData[0];
                    if(tag2.equals("face"))
                        if(splitTutorialData[1].equals("smile"))
                        {
                            smileNumber++;
                            break;
                        }
                    if(tutorialData[j].length() == 0 || tag2.equals("funnel")|| tag2.equals("square")|| tag2.equals("challenge")|| tag2.equals("settool")|| tag2.equals("settext")|| tag2.equals("question")|| tag2.equals("end")|| tag2.equals("image")|| tag2.equals("imagenextout")|| tag2.equals("sound")|| tag2.equals("face"))
                        smileNumber++;
                }
                if(j==tutorialDataNumber)   // NOT FOUND
                    smileNumber = operationCount/2 + 1;
                
                for(j=i+1;j<tutorialDataNumber;j++)
                {
                    splitTutorialData = tutorialData[j].split(":");
                    String tag2 = splitTutorialData[0];
                    if(tag2.equals("face"))
                        if(splitTutorialData[1].equals("sad"))
                        {
                            sadNumber++;
                            break;
                        }
                    if(tutorialData[j].length() == 0 || tag2.equals("funnel")|| tag2.equals("square")|| tag2.equals("challenge")|| tag2.equals("settool")|| tag2.equals("settext")|| tag2.equals("question")|| tag2.equals("end")|| tag2.equals("image")|| tag2.equals("imagenextout")|| tag2.equals("sound")|| tag2.equals("face"))
                        sadNumber++;
                }
                if(j==tutorialDataNumber)   // NOT FOUND
                    sadNumber = operationCount/2 + 1;
                
                operateLine += ":"+smileNumber;
                operateLine += ":"+sadNumber;
                
                serifCount = 0;
                continue;
            }

            serifCount++;
            
            serif[serifTotalCount++] = tutorialData[i];
        }
    
        // END OF FILE
        
        System.out.println("op"+operationCount+":"+operate[operationCount-1]);
    
        if(operateLine.equals(""))
            operate[operationCount++] = String.valueOf(serifCount);
        else if(face)
            operate[operationCount++] = String.valueOf(serifCount) +":"+String.valueOf(serifTotalCount-1)+operateLine;
        else
            operate[operationCount++] = String.valueOf(serifCount) + operateLine;
        
        if(!operate[operationCount-2].equals("end"))
        {
            operate[operationCount++] = "end";
            operate[operationCount++] = "1";
        }

        for(int i=0;i<serifTotalCount;i++)
            System.out.println((i+1)+" > "+serif[i]);
        for(int i=0;i<operationCount;i++)
            System.out.println((i+1)+" > "+operate[i]);
    }
    
    public static void setSerifPath(Control control)
    {
        serifPath = control.absolutePath+"source"+ File.separator + "Tutorial" +File.separator+"serif"+File.separator;
    }
    
    public static void writeTimeLog(String comment)
    {
        Calendar calendar = Calendar.getInstance();

        int month       = calendar.get(Calendar.MONTH);
        int day         = calendar.get(Calendar.DAY_OF_MONTH);
        int hour        = calendar.get(Calendar.HOUR_OF_DAY);
        int minute      = calendar.get(Calendar.MINUTE);
        int second      = calendar.get(Calendar.SECOND);
        
        try{
            PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(serifPath+"TutorialLog.txt",true)));
            
            pw.println(String.valueOf(month + 1)+ "/" +
                       String.valueOf(month + 1) + "/" +
                       String.valueOf(day)       + "/" + " " +
                       String.valueOf(hour)      + ":" +
                       String.valueOf(minute)    + ":" +
                       String.valueOf(second) + ":::"+ mode + "-"+ missionNumber +">>"+comment);
            pw.close();
            
        }catch(IOException e){
            System.out.println("LogError!! in writeTimeLog");
        }
    }
    
    //CREATE CLEAR FLAG
    //episode = mission
    public static boolean clearFlagCheckOperation(int episodeNumber, int modeNumber)//1,4,7,10
    {
        String clearData[];
        clearData = FILEIO.TextFileAllReadCodeArray(new File(serifPath+"clearCheckOperation.txt"));
        
        if(episodeNumber > Integer.parseInt(clearData[(int)(modeNumber/3)]))
            return false;
        else
            return true;
    }
    //episode = mission
    public static boolean clearFlagCheckTool(int episodeNumber, int modeNumber)
    {
        String clearData[];
        clearData = FILEIO.TextFileAllReadCodeArray(new File(serifPath+"ClearCheckTool.txt"));
        
        String clearDataTemp[] = clearData[(int)(modeNumber/3)].split(",");
        
        if(clearDataTemp[episodeNumber-1].equals("0"))
            return false;
        else
            return true;
    }
    //episode = mission
    public static boolean clearFlagCheckMining(int episodeNumber, int modeNumber)
    {
        String clearData[];
        clearData = FILEIO.TextFileAllReadCodeArray(new File(serifPath+"clearCheckMining.txt"));
        
        if(episodeNumber == Integer.parseInt(clearData[(int)(modeNumber/3)-1])) // different from clearCheckOperation
            return false;
        else
            return true;
    }
    
    
    
    //episode = mission
    public static void clearCheckOperation(int episodeNumber, int voiceCount, int modeNumber)//1,4,7,10
    {
        if(voiceCount == 1)
            try{
                String clearData[];
                clearData = FILEIO.TextFileAllReadCodeArray(new File(serifPath+"clearCheckOperation.txt"));
                
                if(episodeNumber > Integer.parseInt(clearData[(int)(modeNumber/3)]))
                {
                    clearData[(int)(modeNumber/3)] = String.valueOf(episodeNumber);
                    
                    PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(serifPath+"clearCheckOperation.txt")));
                    for(int i=0;i<4;i++)
                        pw.println(clearData[i]);
                    pw.close();
                }
                
            }catch(IOException e){
                System.out.println("LogError!! in clearCheckOperation "+modeNumber);
            }
    }
    //episode = mission
    public static void clearCheckTool(int episodeNumber, int voiceCount, int modeNumber)
    {
        if(voiceCount == 1)
            try{
                String clearData[];
                clearData = FILEIO.TextFileAllReadCodeArray(new File(serifPath+"ClearCheckTool.txt"));
                
                String clearDataTemp[] = clearData[(int)(modeNumber/3)].split(",");

                if(clearDataTemp[episodeNumber-1].equals("0"))
                {
                    clearDataTemp[episodeNumber-1] = "1";
                
                    PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(serifPath+"ClearCheckTool.txt")));
                    for(int i=0;i<4;i++)
                        if(i != (int)(modeNumber/3))
                            pw.println(clearData[i]);
                        else
                        {
                            for(int j=0;j<subMissionNumber[modeNumber]-1;j++)
                                pw.print(clearDataTemp[j]+",");
                            pw.println(clearDataTemp[subMissionNumber[modeNumber]-1]);
                        }
                    pw.close();
                }
                
            }catch(IOException e){
                    System.out.println("LogError!! in clearCheckTool "+modeNumber);
            }
    }
    //episode = mission
    public static void clearCheckMining(int episodeNumber, int voiceCount, int modeNumber)
    {
        if(voiceCount == 1)
            try{
                String clearData[];
                clearData = FILEIO.TextFileAllReadCodeArray(new File(serifPath+"clearCheckMining.txt"));
                
                if(episodeNumber == Integer.parseInt(clearData[(int)(modeNumber/3)-1])) // different from clearCheckOperation
                {
                    clearData[(int)(modeNumber/3)-1] = String.valueOf(episodeNumber+1);
                
                    PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(serifPath+"clearCheckMining.txt")));
                    for(int i=0;i<4;i++)
                        pw.println(clearData[i]);
                    pw.close();
                }
                
            }catch(IOException e){
                System.out.println("LogError!! in clearCheckMining "+modeNumber);
            }
    }
    
    public static void disposeOldWindow()
    {
        switch(nextDisposeWindow)
        {
            case 1:
                if(popForAssist != null)
                {
                    popForAssist.closeWindow();
                    popForAssist.dispose();
                }
                popForAssist = new PopUpForAssist(charaX,charaY,150,200,true,control,"normal");
                break;
            case 2:
                if(popForFunnel != null)
                {
                    popForFunnel.dispose();
                    popForFunnel = null;
                }
                break;
            case 3:
                if(popForSerif != null)
                {
                    popForSerif.dispose();
                    popForSerif = null;
                }
                if(popForQuestion != null)
                {
                    popForQuestion.dispose();
                    popForQuestion = null;
                }
                if(popForFunnel != null)
                {
                    popForFunnel.dispose();
                    popForFunnel = null;
                }
                break;
            case 4:
                if(popForSquare != null)
                {
                    popForSquare.dispose();
                    popForSquare = null;
                }
                break;
            case 5:
                if(image2 != null)
                {
                    image2.dispose();
                    image2 = null;
                }
                break;
                
        }
        nextDisposeWindow = 0;
    }
    
    //go: true -> go, false -> back(Right button click)
    public static boolean SerifControl(int operationNumber, boolean go)
    {
        int color = 1;
        
        if(constructorExecuted == false)
        {
            System.out.println("Constractor NOT executed");
            fromModule = false;     //QUIT TUTORIAL
            return true;     //QUIT TUTORIAL
        }
        
        if(operationNumber==0 && go)    //character and moon, only once
        {
            popForAssist = new PopUpForAssist(charaX,charaY,150,200,true,control,"normal");
            popForMoveCharacter = new PopUpForMoveCharacter(charaX+100, charaY-100, control.absolutePath);
            goVoiceNumber = 0;
            currentVoiceNumber = -1;
        }
        
        String operation = operate[operationNumber*2];
        String operationData[] = operate[operationNumber*2+1].split(":");
        goVoiceNumber = Integer.parseInt(operationData[0]);
        
        System.out.println("-------------:go="+go);
        System.out.println("operationNumber="+operationNumber+":"+operation);
        System.out.println("currentVoiceNumber="+currentVoiceNumber);           //Using static variable
        System.out.println("goVoiceNumber="+goVoiceNumber);
        
        if(go == false)
        {
            String line[] = operate[(operationNumber+1)*2+1].split(":");
            backVoiceNumber = Integer.parseInt(line[0]);
            
            System.out.println("backVoiceNumber="+backVoiceNumber);
            System.out.println("["+operation+" <- "+operate[(operationNumber+1)*2]+"]");
            
            if(operation.equals("question") || operation.equals("challenge") || operation.equals("settool")|| operation.equals("settext")|| operation.equals("end"))
            {
                System.out.println("Can't go back");
                return false;
            }
        }
        
        if(operation.equals("end")) //0:not clear, 1:clear
        {
            writeTimeLog("END "+String.valueOf(goVoiceNumber));
            
            if(image2 != null)
                image2.dispose();
            
            if(modeNumber % 3 == 1)
                clearCheckOperation(missionNumber, goVoiceNumber, modeNumber);
            if(modeNumber % 3 == 2)
                clearCheckTool(missionNumber, goVoiceNumber, modeNumber);
            if(modeNumber % 3 == 0)
                clearCheckMining(missionNumber, goVoiceNumber, modeNumber);
            
            CloseAllSmallChapterWindow();
            
            if(fromModule == false)
                PopPanelForChapter(modeNumber, control);
            
            if(modeNumber % 3 == 2)
            {
                if(fromModule == false)
                {
                    int m0[] = {40,19,1};
                    int v0[] = {3,3,1};
                    int t0[] = {0,0,0};
                    int s0[] = {1,2,2};
                    control.panelSet(m0,v0,t0,s0);
                }
                else
                {
                    //back
                    for(int i=0;i<control.sp1.lastTextID.length;i++)
                        control.sp1.lastTextID[i] = 0;
                    
                    control.panelSet(control.sp1.lastMiningID, control.sp1.lastVisualizationID, control.sp1.lastTextID, control.sp1.lastBalancedPanelSizeX);
                    control.characterTutorial = 0;
                    control.setCharacterTutorialButton();
                }
            }

            fromModule = false;     //QUIT TUTORIAL
            return true;     //QUIT TUTORIAL
        }
        
        if(go == true)
            currentVoiceNumber += goVoiceNumber;
        else
            if(currentVoiceNumber - backVoiceNumber >= 0)
                currentVoiceNumber -= backVoiceNumber;
        
        System.out.println("NEW: currentVoiceNumber="+currentVoiceNumber);
        
        disposeOldWindow();        //dispose old Window
        color = 1;

        if(operation.equals("normal")){}
        
        if(operation.equals("funnel"))
        {
            buttonSearch(Integer.parseInt(operationData[1]), Integer.parseInt(operationData[2]));   //calculate FunnelX, FunnelY
            popForFunnel = new PopUpForFunnel(FunnelX, FunnelY, control.absolutePath);
            
            nextDisposeWindow = 2;  //funnel window
        }
        
        if(operation.equals("image"))
        {            
            if(image2 != null)
                image2.dispose();
            
//            image2 = new ImagePanel2(control.absolutePath, Integer.parseInt(operationData[1]));
            image2 = new ImagePanel2(control.absolutePath, operationData[1]);
            image2.setVisible(true);
        }
        
        if(operation.equals("imagenextout"))
        {
            if(go == true)
                nextDisposeWindow = 5; //image2 window
            else
            {
                if(image2 != null)
                    image2.dispose();
                
//                image2 = new ImagePanel2(control.absolutePath, Integer.parseInt(operationData[1]));
                image2 = new ImagePanel2(control.absolutePath, operationData[1]);
                image2.setVisible(true);
            }
        }
        
        if(operation.equals("sound"))
        {
            SoundPlay soundPlay = new SoundPlay(control.absolutePath, operationData[1]);
        }
        
        if(operation.equals("square"))
        {
            areaSearch(Integer.parseInt(operationData[1]), Integer.parseInt(operationData[2]));
            popForSquare = new PopUpForSquare(SquareX,SquareY,SquareWidth,SquareHeight, control);

            nextDisposeWindow = 4; //square window
        }
        
        if(operation.equals("question"))
        {
            boolean sound = true;

            popForQuestion = new PopUpForQuestion(control,operationNumber,operationData[1],operationData[2],operationData[3],operationData[4],Integer.parseInt(operationData[5]),Integer.parseInt(operationData[6]),Integer.parseInt(operationData[7]), sound);
            
            
            operationNumber--;  //Do not proceed

            nextDisposeWindow = 3; //serif by color
            color = 2;
        }
        
        if(operation.equals("challenge"))
        {
            numberForAction = operationNumber;
            
            actionNumber = Integer.parseInt(operationData[1]);
            
            System.out.println("===actionNumber==="+actionNumber+"=======");

            operationNumber--;  //Do not proceed

            nextDisposeWindow = 3; //serif by color
            color = 3;
            
            if(Integer.parseInt(operationData[1]) != 2003)  //Interpretation
                if(buttonSearch(Integer.parseInt(operationData[1]), Integer.parseInt(operationData[2])))   //calculate FunnelX, FunnelY
                    popForFunnel = new PopUpForFunnel(FunnelX, FunnelY, control.absolutePath);
        }
        
        if(operation.equals("settool"))
        {
            numberForAction = operationNumber;
            
            changeMiningNumber = Integer.parseInt(operationData[1]);
            changeVisualizationNumber = Integer.parseInt(operationData[2]);
            
            System.out.println("===changeMiningNumber==="+changeMiningNumber+"=======");
            System.out.println("===changeVisualizationNumber==="+changeMiningNumber+"=======");
            
            operationNumber--;  //Do not proceed
            
            nextDisposeWindow = 3; //serif by color
            color = 3;
        }
        
        if(operation.equals("settext"))
        {
            numberForAction = operationNumber;
            
            changeTextFilename = operationData[1];
            
            System.out.println("===changeTextFilename==="+changeMiningNumber+"=======");
            
            operationNumber--;  //Do not proceed
            
            nextDisposeWindow = 3; //serif by color
            color = 3;
        }

        if(operation.equals("face"))
        {
            currentVoiceNumber = Integer.parseInt(operationData[1]);    // OVER WRITE
 
            if(popForAssist != null)
            {
                popForAssist.closeWindow();
                popForAssist.dispose();
                popForAssist = null;
            }
            popForAssist = new PopUpForAssist(charaX,charaY,150,200,true,control,operationData[2]);
            
            nextDisposeWindow = 1; //character by face
        }
 
        //create New Serif Window
        createPopForSerif(charaX, charaY, goVoiceNumber, currentVoiceNumber, operationNumber, color);
        
        currentOperationNumber = operationNumber;
        currentColor = color;
        

        
        return true;
    }
    
    static int currentOperationNumber;
    static int currentColor;
    
    //MOON
    public static void characterMoveReverse()
    {
        int windowSizeX=1024;
        try{
            GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
            DisplayMode displayMode = env.getDefaultScreenDevice().getDisplayMode();
            
            windowSizeX = displayMode.getWidth();
        }
        catch(Exception e){}
        
        charaX = (windowSizeX-150)-charaX;
        popForAssist.setLocation(charaX, charaY);
        if(popForSerif != null)
        {
            popForSerif.dispose();
            popForSerif = null;
        }
        createPopForSerif(charaX, charaY, goVoiceNumber, currentVoiceNumber, currentOperationNumber, currentColor);

        popForMoveCharacter.setLocation(charaX+100,charaY-100);
    }
    
    public static void createPopForSerif(int charaX, int charaY, int voiceCount, int voiceCount2, int number, int color)
    {
        String displaySerif[] = new String[voiceCount];
        for(int i=0;i<voiceCount;i++)
            displaySerif[i] = serif[voiceCount2 - voiceCount + 1 + i];
        popForSerif = new PopUpForSerif(charaX, charaY, 800, 130, true, number, displaySerif, color, control, voice, clearFlag);
    }
    
    //For funnel
    public static boolean buttonSearch(int buttonNumber, int panelNumber)
    {
        JComponent button = null;
//        int panelNumber = 0;
        Point position = null;
        int sizeX=0, sizeY=0;
        
        boolean buttonFound = false;
        
        FunnelX = FunnelY = 0;
        
        //For operationPanel

        if(buttonNumber >= 1000001 && buttonNumber <= 1000005)
        {
            buttonNumber -= 1000001;
            /*
            button = control.panel[panelNumber].mining[control.panel[panelNumber].selected_module].operationPanel;
            position = button.getLocationOnScreen();
        
            FunnelX = (int)position.getX();
            FunnelY = (int)position.getY();
        
            sizeX = button.getWidth();
            sizeY = button.getHeight();
            
            switch(buttonNumber)
            {
                case 1000001:
                    FunnelX = FunnelX+sizeX/2;
                    FunnelY = FunnelY+(sizeY/8/2);
                    break;
                    
                case 1000002:
                    FunnelX = FunnelX+sizeX/2;
                    FunnelY = FunnelY+(sizeY/8/2)+(sizeY/8);
                    break;
                    
                case 1000003:
                    FunnelX = FunnelX+sizeX/4/2;
                    FunnelY = FunnelY+(sizeY/2/2);
                    break;
                    
                case 1000004:
                    FunnelX = FunnelX+sizeX/4/2+sizeX/4*2;
                    FunnelY = FunnelY+(sizeY/2/2);
                    break;
                    
                case 1000005:
                    FunnelX = FunnelX+sizeX/4/2+sizeX/4*3;
                    FunnelY = FunnelY+(sizeY/2/2);
                    break;
            }

            FunnelX -= 15;
            FunnelY -= 15;

            return true;
             */
        }
        

        if(panelNumber > control.panelNumber)
            panelNumber = 0;
        
        //For operation Panel in MiningModule
        int buttonCount=0;
        if(control.panel[panelNumber].mining[control.panel[panelNumber].selected_module].button != null)
        {
            if(buttonNumber < control.panel[panelNumber].mining[control.panel[panelNumber].selected_module].button.length)
                button = control.panel[panelNumber].mining[control.panel[panelNumber].selected_module].button[buttonNumber];
            buttonCount = control.panel[panelNumber].mining[control.panel[panelNumber].selected_module].button.length;
        }

        if(button == null)
            if(control.panel[panelNumber].mining[control.panel[panelNumber].selected_module].toggleButton != null)
                if(buttonNumber - buttonCount < control.panel[panelNumber].mining[control.panel[panelNumber].selected_module].toggleButton.length)
                    button = control.panel[panelNumber].mining[control.panel[panelNumber].selected_module].toggleButton[buttonNumber - buttonCount];
        
        //For buttons
        switch(buttonNumber)
        {
            case 1001:
                button = control.bt55;
                break;
            case 1002:
                button = control.bt52;
                break;
            case 1003:
                button = control.bt10;
                break;
            case 1004:
                button = control.bt40;
                break;
            case 1005:
                button = control.bt50;
                break;
            case 1006:
                button = control.bt71;
                break;
            case 1007:
                button = control.bt90;
                break;
            case 1008:
                button = control.btx;
                break;
            case 1009:
                if(control.sp1.mode == 2)
                    button = control.btxImage;
                else if(control.sp1.mode == 3)
                    button = control.btxTree;
                break;
            case 1010:
                button = control.bt72;
                break;

            case 1011:
                button = control.bt70;
                break;
            case 1012:
                button = control.bt20;
                break;
            case 1013:
                button = control.bt30;
                break;
            case 1014:
                button = control.btTutorial;
                break;
            case 1015:
                button = control.btxx;
                break;
            case 1016:
                button = control.btxxx;
                break;
            case 1023:
                button = control.bt81;
                break;
                case 1024:
                case 2003:
                    button = control.bt79;
                    break;
                
                
            case 1017:
                button = control.bt77;
                break;
            case 1018:
                button = control.bt78;
                break;
            case 1019:
                button = control.bt0;
                break;
            case 1020:
                button = control.bt00;
                break;
            case 1021:
                button = control.bt99;
                break;
            case 1022:
                button = control.bt60;
                break;
                
            case 1025:
                button = control.btd1;
                break;
            case 1026:
                button = control.btd2;
                break;
            case 1027:
                button = control.btd3;
                break;
            case 1028:
                button = control.btxTree;
                break;
                
            case 2001:
                button = control.panel[panelNumber].moduleSelect;
                break;
            case 2002:
                button = control.panel[panelNumber].moduleSelectImage;
                break;
//            case 2003:
  //              button = control.panel[panelNumber].interpretation;
    //            break;
            case 2004:
                button = control.panel[panelNumber].reExecution;
                break;

                
            case 3001:
                button = control.panel[panelNumber].mining[control.panel[panelNumber].selected_module].combinationPanel.panelDeleteButton;
                break;
            case 3002:
                button = control.panel[panelNumber].mining[control.panel[panelNumber].selected_module].combinationPanel.panelKeepButton;
                break;
            case 3003:
                button = control.panel[panelNumber].mining[control.panel[panelNumber].selected_module].combinationPanel.panelSetButton;
                break;
            case 3004:
                button = control.panel[panelNumber].mining[control.panel[panelNumber].selected_module].combinationPanel.panelCaptureButton;
                break;
            case 3005:
                button = control.panel[panelNumber].mining[control.panel[panelNumber].selected_module].combinationPanel.displayReadmeButton;
                break;
            case 3006:
                button = control.panel[panelNumber].mining[control.panel[panelNumber].selected_module].combinationPanel.partialDocument;
                break;
            case 3007:
                button = control.panel[panelNumber].mining[control.panel[panelNumber].selected_module].combinationPanel.displayDiffButton;
                break;
            case 3008:
                button = control.panel[panelNumber].mining[control.panel[panelNumber].selected_module].combinationPanel.characterTutorialButton;
                break;


        }

        if(button != null)
        {
            position = button.getLocationOnScreen();
            sizeX = button.getWidth();
//            sizeY = button.getHeight();
            FunnelX = (int)position.getX();
            FunnelY = (int)position.getY();
            FunnelX += sizeX/2;
            
            return true;
        }
        else
            return false;
    }
    
    //For square
    public static void areaSearch(int areaNumber, int panelNumber)
    {
        Point position;
        Component panel = null;
        SquareX = SquareY = 0;
        SquareWidth = SquareHeight = 0;
        
        if(panelNumber > control.panelNumber)
            panelNumber = 0;
        
        switch(areaNumber)
        {
            case 1:
                panel = control.mainf;
                break;
            case 2:
                panel = control.pop;
                break;
            case 3:
                panel = control.panel[panelNumber];
                break;
            case 4:
                panel = control.panel[panelNumber].mining[control.panel[panelNumber].selected_module].operationPanel;
                break;
        }
 
        if(panel != null)
        {
            position = panel.getLocationOnScreen();
 
            SquareX = (int)position.getX();
            SquareY = (int)position.getY();
 
            SquareWidth = panel.getWidth();
            SquareHeight = panel.getHeight();
        }
    }

    public static void CharaStanding(int X,int Y)
    {
        charaX = X;
        charaY = Y;
    }

    public static void nextSerif(int action)    // Go next if specific action indicated by action comes
    {
        if(actionNumber == 0)
            return;
        
        if(actionNumber == action)
        {
            actionNumber = 0;
            SerifControl(numberForAction + 1, true);
        }
    }
    
    public static void PanelSelectCheck()
    {
        if(changeMiningNumber == 0 && changeVisualizationNumber == 0)
            return;
        
        if(control.isSetModule(changeMiningNumber, changeVisualizationNumber))
        {
            changeMiningNumber = 0;
            changeVisualizationNumber = 0;
            SerifControl(numberForAction + 1, true);
        }
    }
    
    public static void TextSelectCheck(String filename)    //called from textDataLoading() in Control.java
    {
        if(changeTextFilename.equals(""))
            return;
        
        if(filename.equals(changeTextFilename))
        {
            changeTextFilename = "";
            SerifControl(numberForAction + 1, true);
        }
    }
    
    //Initialize Log Data
    public static void DeleteLog(Control cont)
    {
        System.out.println("Initialize Character Assist Tutorial Log");
        
        control = cont;
        
        if(countSubmission == 0)
            countSubMissionNumber();
        
        try{
            //coslog delete
            PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(serifPath+"coslog.txt")));
            pw.println("0");
            pw.println("0");
            pw.close();
            
            //0: SL0
            pw = new PrintWriter(new BufferedWriter(new FileWriter(serifPath+"ClearChecker0.txt")));
            pw.println("0");
            pw.close();
            
            pw = new PrintWriter(new BufferedWriter(new FileWriter(serifPath+"ClearCheckOperation.txt")));
            for(int i=0;i<4;i++)
                pw.println("0");
            pw.close();
            
            pw = new PrintWriter(new BufferedWriter(new FileWriter(serifPath+"ClearCheckTool.txt")));
            for(int i=0;i<4;i++)
            {
                for(int j=0;j<subMissionNumber[i*3+2]-1;j++)
                    pw.print("0,");
                pw.println("0");
            }
            pw.close();

            pw = new PrintWriter(new BufferedWriter(new FileWriter(serifPath+"ClearCheckMining.txt")));
            for(int i=0;i<4;i++)
                pw.println("0");
            pw.close();

        }catch(IOException e){
            System.out.println("Error on DeleteLog() in StoryControl.java");
        
        }
    }
    
    public static int fileCount(String path, int startCount)
    {
        File file;
        int count=0;
        
        for(int i=startCount; i<100; i++, count++)
        {
            String filename = path+i+".txt";
            file = new File(filename);
            
            //            System.out.println("Checking file"+filename);
            
            if(!file.exists())
                break;
        }
        
        return count;
    }
    
    //true: clear data initialized, false: not initialized
    public static boolean countModuleTutorial()
    {
        int tutorialCount[] = new int[4];
        int moduleIndex[][] = new int[4][maxModuleTutorial];
        int mode;
        String moduleName;
        String tutorialFilename;
        String tutorialClearFilename;
        File file;
        
        for(int i=0;i<4;i++)
            tutorialCount[i]=0;
        
        for(int i=0;i<control.readModuleData.module_names.length;i++)
        {
            mode = control.readModuleData.mining[i].getUseMode();
            moduleIndex[mode][tutorialCount[mode]++] = i;
        }
        
        System.out.println("Tutorial Check ");
        
        for(int i=0;i<4;i++)
        {
            moduleTutorialCount[i] = 0;
            System.out.println("mode= "+i+" module Number= "+tutorialCount[i]);
            for(int j=0;j<tutorialCount[i];j++)
            {
                moduleName = control.readModuleData.module_names[moduleIndex[i][j]];
                
                tutorialFilename = control.absolutePath + "module" + File.separator + "MiningModules" + File.separator + moduleName + File.separator + moduleName+"Tutorial.txt";
                tutorialClearFilename = control.absolutePath + "module" + File.separator + "MiningModules" + File.separator + moduleName + File.separator + moduleName+"TutorialClear.txt";
                
                file = new File(tutorialFilename);
                int exist = 0;
                if(file.exists())
                {
                    exist = 1;
                    moduleTutorialIndex[i][moduleTutorialCount[i]] = moduleIndex[i][j];
                    moduleTutorialFilename[i][moduleTutorialCount[i]] = tutorialFilename;
                    moduleTutorialClearFilename[i][moduleTutorialCount[i]] = tutorialClearFilename;
                    moduleNameInJapanese[i][moduleTutorialCount[i]] = control.readModuleData.miningModuleNamesInJapanese[moduleIndex[i][j]];
                    moduleTutorialCount[i]++;
                }
                
                System.out.println(tutorialFilename+" "+exist);
            }
        }
        
        
        //        String tutorialClearFilename = control.absolutePath + "module" + File.separator + "MiningModules" + File.separator + moduleName + File.separator + moduleName+"TutorialClear.txt";
        
        String modeLabel[] = {"SL2","L2","N2","A2"};
        for(int j=0;j<4;j++)
        {
            String copiedFilepath = control.absolutePath + "source" + File.separator + "Tutorial" + File.separator + "serif" + File.separator + modeLabel[j] + File.separator;
            
            File dir = new File(copiedFilepath);
            File[] fileArray=dir.listFiles();
            for(int i=0;i<fileArray.length;i++)
                fileArray[i].delete();
        
            for(int i=0;i<moduleTutorialCount[j];i++)
                EXECUTE.fileReadCopy(moduleTutorialFilename[j][i], copiedFilepath+(i+1)+".txt", "SHIFT-JIS", false);
        }
        
        ////////
        String clearCheckerTool[];
        clearCheckerTool = FILEIO.TextFileAllReadCodeArray(new File(control.absolutePath + "source" + File.separator + "Tutorial" + File.separator + "serif" + File.separator+ "ClearCheckTool.txt"));
        boolean difference[] = {false,false,false,false};
        boolean change = false;
        
        if(clearCheckerTool.length < 4)
        {
            try{
                PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(control.absolutePath + "source" + File.separator + "Tutorial" + File.separator + "serif" + File.separator+ "ClearCheckTool.txt")));
                
                for(int i=0;i<4;i++)
                {
                    for(int j=0;j<moduleTutorialCount[i]-1;j++)
                        pw.print("0,");
                    pw.println("0");
                }
                pw.close();
                
            }catch(IOException e){
                System.out.println("Writing Error in ChapterPanel Constructor at countModuleTutorial in StoryControl.");
            }
            return true;
        }
        
        for(int i=0;i<4;i++)
        {
            String clearCheck[] = clearCheckerTool[i].split(",");
            if(moduleTutorialCount[i] != clearCheck.length)
            {
                difference[i] = true;
                change = true;
            }
        }
        
        if(change == true)
        {
            try{
                PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(control.absolutePath + "source" + File.separator + "Tutorial" + File.separator + "serif" + File.separator+ "ClearCheckTool.txt")));
                
                for(int i=0;i<4;i++)
                {
                    if(difference[i] == true)
                    {
                        for(int j=0;j<moduleTutorialCount[i]-1;j++)
                            pw.print("0,");
                        pw.println("0");
                    }
                    else
                        pw.println(clearCheckerTool[i]);
                }
                pw.close();
                
            }catch(IOException e){
                System.out.println("Writing Error in ChapterPanel Constructor at countModuleTutorial in StoryControl.");
            }
        }
        
        return change;
    }
    
    public static int countSubmission = 0;
    public static void countSubMissionNumber()
    {
        String modeName[] = {"","SL","SL2","SL3","L","L2","L3","N","N2","N3","A","A2","A3"};
        int startNumber[] = {0,   2,    1,    0,  1,   1,   0,  1,   1,   0,  1,   1,   0};
        //        int missionNumber[] = {0, 11,8,12,  9,2,6,  8,10,9,  6,17,9};
        int missionNumber[] = new int[13];
        
        /////
        countModuleTutorial();
        
        missionNumber[0] = 0;
        
        System.out.println("---Count SubMissionNumbers in StoryPanel---");
        
        for(int i=1;i<13;i++)
        {
            int count;
            
            count = fileCount(control.absolutePath + "source" + File.separator + "Tutorial" + File.separator + "serif" + File.separator + modeName[i] + File.separator, startNumber[i]);
            
            
            //            System.out.println(modeName[i]+":"+count);
            
            if(i==1)
                missionNumber[i] = count+1;
            else
                missionNumber[i] = count;
            
            System.out.print(missionNumber[i]+" ");
        }
        System.out.println("");
        
        for(int i=0;i<13;i++)
            subMissionNumber[i] = missionNumber[i];
        
        countSubmission = 1;
        
    }
    
    
    
    
    

    public static void ImagePop(Control control, int count)
    {
        image = new ImagePanel(control, count);
        image.setVisible(true);
    }

    public static void PopPanelForChapter(int number, Control control)
    {
       serifPath = control.absolutePath+"source"+ File.separator + "Tutorial" +File.separator+"serif"+File.separator;
        
        if(number==1)
        {
            String zero="";
            
            try{
                File file4 = new File(serifPath+"ClearChecker0.txt");
                BufferedReader br4 = new BufferedReader(new FileReader(file4));
                zero = br4.readLine();
                br4.close();
            }catch(FileNotFoundException e){
                System.out.println(e);
            }catch(IOException e){
                System.out.println(e);
            }

            if(zero.equals("0"))
            {
                ImagePop(control, 1);   ////Chapter0
                return;
            }
        }
        popForChapter[number] = new PopUpForChapter(200, 100, 400, 400, control, number);   //Chapter1-12
    }

    public static void PopPanel(Control control, int number)
    {
        popForStory[number] = new PopUpForStory(200, 100, 400, 400, control, number);
    }

    public static void CloseAllSmallChapterWindow()
    {
        if(popForAssist != null)
        {
            popForAssist.closeWindow();
            popForAssist.dispose();
            popForAssist = null;
        }
        if(popForMoveCharacter != null)
        {
            popForMoveCharacter.dispose();
            popForMoveCharacter = null;
        }
        if(popForSerif != null)
        {
            popForSerif.dispose();
            popForSerif = null;
        }
        if(popForFunnel != null)
        {
            popForFunnel.dispose();
            popForFunnel = null;
        }
        if(popForSquare != null)
        {
            popForSquare.dispose();
            popForSquare = null;
        }
        if(popForQuestion != null)
        {
            popForQuestion.dispose();
            popForQuestion = null;
        }
        if(image != null)
        {
            image.dispose();
            image = null;
        }
        if(image2 != null)
        {
            image2.dispose();
            image2 = null;
        }
        
        nextDisposeWindow=0;
        
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>RECOVER TEXT>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        
        //RECOVER BACKUP TEXT
        if(control != null) //for environment initialization
        if(control.last_original_file != null)
        {
            System.out.println("RECOVER TEXT from "+control.text.sourceFilename.substring(0, control.text.sourceFilename.length()-1)+" >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>BACKUP CURRENT TEXT = "+control.last_original_file);
            control.autoTextLoading(control.last_original_file);
            control.last_original_file = null;

        }
    }
    
    public static void CloseAllWindows()
    {
        for(int i=1;i<=7;i++)
            if(popForStory[i] != null)
            {
                popForStory[i].dispose();
                popForStory[i] = null;
            }
        
        for(int i=1;i<=12;i++)
            if(popForChapter[i] != null)
            {
                popForChapter[i].dispose();
                popForChapter[i] = null;
            }
        
        CloseAllSmallChapterWindow();
    }
}

