/* Program: Questionnaire
 * Author: Rytis Umbrasas
 * School: Vilnius Lyceum
 * IDE: NetBeans 4.1
 */

import java.io.*;
import java.util.*;

class questions extends database{
    
    final String filename = conf.RootDirectory+conf.QuestionsFileName;
    final String index_filename = conf.RootDirectory+conf.IndexFileName;
    int id;
    String question, multimedia;
    String[] choices = new String[5];
    
    private void parse_line(String s){
    /* Parses question CSV line and assigns values to class variables */    
        int start = 1;
        
	for (int r = 0; r < 8; r++){
            int end = s.indexOf("\"", start);
            while (s.charAt(end+1) == '\"')
		end = s.indexOf("\"", end + 2);
            String tmp = s.substring(start, end);
            tmp = remove_quotes(tmp);
            start = end + 3;
            switch (r){
		case 0: id = Integer.parseInt(tmp);break;
		case 1: multimedia = tmp;break;
                case 2: question = tmp;break;
                case 3: choices[0] = tmp;break;
		case 4: choices[1] = tmp;break;
                case 5: choices[2] = tmp;break;
                case 6: choices[3] = tmp;break;
		case 7: choices[4] = tmp;break;
            }
        }
		
    }
    
    private int count_csv_fields(String s){
    /* Finds the number of fields in a CSV line */    
        int r = 1;
        
        while (s.indexOf("\",\"") != -1){
            s = s.substring(s.indexOf("\",\"")+3, s.length());
            r++;
        }
        
        return r;
    }
           
    public String[][] get_all_questions(boolean with_id) throws IOException{
    /* Gets all questions from the questions file name sorted by order defined in
     * questions index file
     */
        
        int[] order = get_line_order(index_filename);
        String[][] questions;
        if (!with_id)
            questions = new String[order.length][7];
        else
            questions = new String[order.length][8];
        
        int count_lines = get_total_lines(filename);
        
        for (int r = 0; r<order.length; r++) {
            
            if (order[r] >= count_lines){
                System.err.println("Invalid question id: "+order[r]+" " +
                        "removing from index file.");
                order[r] = -1;
                updateQuestionIndex(order);
                
                return get_all_questions(with_id);
            }
            else if (count_csv_fields(get_line(filename, order[r])) != 8){
                System.err.println("Invalid question CSV format "+order[r]+". " +
                        "Removing from the index file.");
                order[r] = -1;
                updateQuestionIndex(order);
                
                return get_all_questions(with_id);
            }
            else{
                parse_line(get_line(filename, order[r]));
                
                questions[r][0] = question;
                questions[r][1] = choices[0];
                questions[r][2] = choices[1];
                questions[r][3] = choices[2];
                questions[r][4] = choices[3];
                questions[r][5] = choices[4];
                questions[r][6] = multimedia;
                
                if (with_id)
                    questions[r][7] = Integer.toString(id);
            }
        }
        
        return questions;
    }
        
    private String make_line(int id, String image, String question, String[] choices)
    throws IOException{
    /* Makes a line for a CSV file */
        
        String line = new String();
        if (id == -1)
            line  = "\""+get_total_lines(filename)+"\",";
        else
            line = "\""+id+"\",";
        line += "\""+image+"\",";
        line += "\""+add_quotes(question)+"\",";
        line += "\""+add_quotes(choices[0])+"\",";
	line += "\""+add_quotes(choices[1])+"\",";
	line += "\""+add_quotes(choices[2])+"\",";
        line += "\""+add_quotes(choices[3])+"\",";
	line += "\""+add_quotes(choices[4])+"\",";
        
        return line;
    }

    public void add_question(String image, String question, String[] choices){
    /* Adds a new question to questions file name */
        try {
            File img = new File(image);
            String fn = img.getName();
            
            if (image.compareTo("") != 0 && image.compareTo(conf.RootDirectory+fn) != 0)
                copyFile(image);
            
            String line = make_line(-1, fn, question, choices);
            String index_line = get_line(index_filename, 0);
            if (index_line == null){
                index_line = Integer.toString(get_total_lines(filename));
                add_line(filename, line, false);
            }
            else{
                index_line += " "+Integer.toString(get_total_lines(filename));
                add_line(filename, line, true);
            }
            
            add_line(index_filename, index_line, false);
        }
        catch (Exception e){
            System.err.println(e.toString());
        }
    }
    
    public void update_question(int id, String image, String question, String[] choices)
    throws IOException{
    /* Updates questions file with values defined in the arguments */
        
        File in = new File(image);
        String fn = in.getName();
        
        String l = make_line(id, fn, question, choices);
        String[] contents = new String[get_total_lines(filename)];
        
        if(image.compareTo("") != 0 && image.compareTo(conf.RootDirectory+fn) != 0
                && fn.compareTo(image) != 0)
            try {
                copyFile(image);
            }
            catch (Exception e2){
                System.err.println(e2.toString());
            }
        
        for (int r = 0; r< get_total_lines(filename); r++){
            if(r == id)
                contents[r] = l;
            else
                contents[r] = this.get_line(filename, r);
        }
        
        for (int r = 0; r < contents.length; r++)
            this.add_line(filename, contents[r], (r != 0));
            
    }
    
    public int[] get_line_order(String filename) throws IOException{        
    /* Reads and parses question index file */
        
        String line = this.get_line(filename, 0);
        
        StringTokenizer t;
        if (line == null)
            t = new StringTokenizer(" ");
        else
            t = new StringTokenizer(line);
        int[] order = new int[t.countTokens()];
        int r = 0;
        while(t.hasMoreElements()){
            order[r] = Integer.parseInt(t.nextToken());
            r++;
        }
            
        return order;
    }
    
    public void updateQuestionIndex(int[] index){
    /* Updates question index after swapping, removing or adding a new question */    

        String s = new String();
	for (int r = 0; r < index.length; r++)
            if (index[r] != -1)
                s += Integer.toString(index[r])+" ";
        try{
            add_line(index_filename, s, false);
        }
        catch (Exception e){
            System.err.println(e.toString());
        }
    }

}