/**
 * LICENSE:
 * The MIT License [https://opensource.org/licenses/MIT]:
 * Copyright 2019 William Lam @ HKWTC
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * ---------------------------------------------
 *
 * Project: Student Information System
 * Author : William Lam (BlackPhreak)
 *
 * ---------------------------------------------
 *
 * Used Libraries:
 * 1. Google Gson
 *      + https://github.com/google/gson
 * 2. SQLite
 *      + https://www.sqlite.org/index.html
 *      + https://bitbucket.org/xerial/sqlite-jdbc/downloads/
 */

package me.blackphreak;

import me.blackphreak.CommandHandling.CommandHandler;
import me.blackphreak.CommandHandling.CommandManager;
import me.blackphreak.Debug.Debug;
import me.blackphreak.Student.Types.LocalStudent;
import me.blackphreak.Student.Types.OverseaStudent;

import java.util.HashMap;

public class Main {

    public static void main(String[] args) {
        HashMap<String, Object> opts = new HashMap<>();
    
        for (int i = 0; i < args.length; i++) {
            // always do "++i" to skip the taken option value.
        
            switch (args[i]) {
                case "--config":
                    opts.put("config", args[++i]);
                    break;
            
                case "--save_config":
                    opts.put("save_config", args[++i]);
                    break;
                    
                case "--create-student":
                    opts.put("create-student", args[++i]);
                    break;
                    
                case "-h":
                case "--help":
                    printHelp();
                    return;
            }
        }
    
        /*if (args.length == 0) {
            printHelp();
            return;
        }*/
    
        // uses to ignore next action(option) if false
        boolean doNextAction = true;
        
        // read & execute options with order:
        var config = (String) opts.getOrDefault("config", "");
        FileIO.readConfig(config);
        
        // connect to database
        Database db = Database.getInstance();
        
        // save config
        var save_config = opts.get("save_config");
        if (save_config != null) {
            FileIO.saveConfig();
        }
        
        var createStudent = opts.get("create-student");
        if (createStudent != null) {
            var stu = Lib.jsonToStudent((String)createStudent);
            
            // insert to database
            var sb = new StringBuilder("INSERT INTO Student (StudentID, ChtName, EngName, Address, MobileNum, Nationality, ");
            String sql;
    
            if (stu instanceof LocalStudent) {
                var tmpStu = (LocalStudent)stu;
                
                //StudentID, ChtName, EngName, Address, MobileNum, Nationality, HKID
                sb.append("HKID) VALUES (\"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\");");
        
                sql = String.format(
                        sb.toString(),
                        tmpStu.getStudentID(),
                        tmpStu.getChtName(),
                        tmpStu.getEngName(),
                        tmpStu.getHomeAddress(),
                        tmpStu.getMobileNumber(),
                        tmpStu.getNationality(),
                        tmpStu.getHKID()
                );
            }
            else if (stu instanceof OverseaStudent) {
                var tmpStu = (OverseaStudent)stu;
        
                //StudentID, ChtName, EngName, Address, MobileNum, Nationality, VISA
                sb.append("VISA) VALUES (\"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\");");
        
                sql = String.format(
                        sb.toString(),
                        tmpStu.getStudentID(),
                        tmpStu.getChtName() == null || tmpStu.getChtName().isEmpty()
                                ? null
                                : tmpStu.getChtName(),
                        tmpStu.getEngName(),
                        tmpStu.getHomeAddress(),
                        tmpStu.getMobileNumber(),
                        tmpStu.getNationality(),
                        tmpStu.getVisa()
                );
            }
            else
            {
                Debug.err("Unknown student type.");
                sql = "";
            }
    
            if (Database.getInstance().update(sql) > 0)
                Debug.info("Insertion successful. Exiting...");
            else
                Debug.err("Failed to insert! Exiting...");
            
            doNextAction = false;
        }
        
        if (doNextAction)
        {
            // register commands
            CommandManager.registerCommands();
            
            // command mode (keep looping until exit)
            CommandHandler.printOptions();
        }
        
        // close the db connection
        db.close();
    }
    
    private static void printHelp() {
        System.out.println("----------- Help -----------");
        System.out.println("--config <file>          : Indicate program to use the specific configuration file\n");
        System.out.println("--save_config <file>     : Save the running configuration file.\n");
        System.out.println("--create-student <json>  : Create a student by JSON string (for lazy people =w=).\n");
        System.out.println("-h  --help               : Print this help message\n\n");
    }
}
