package com.yutou.tools.sqlite;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yutou.tools.utils.ConfigTools;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class SQLiteManager {
    protected Connection conn;
    private String url = "jdbc:sqlite:";
    private File sql;


    public void startBatch() {
        try {
            conn.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void closeBatch() {
        try {
            conn.setAutoCommit(true);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void commit() {
        try {
            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    protected SQLiteManager() {

    }
    private void createSql(JSONObject json){
        try {
            sql.mkdirs();
            sql.delete();
            conn = DriverManager.getConnection(url + sql.getAbsolutePath());
        }catch (Exception e){
            e.printStackTrace();
        }
        startBatch();
        JSONArray array=json.getJSONArray("table");
        for (Object o : array) {
            System.out.println("创建表:"+((JSONObject)o).getString("name"));
            createSqlOfTable((JSONObject) o);
        }
        closeBatch();
        ConfigTools.save(ConfigTools.SQLITE, json.getString("file"), json);
    }
    private void createSqlOfTable(JSONObject table) {
        String tableName = table.getString("name");
        try {
            Statement statement = conn.createStatement();
            JSONArray items = table.getJSONArray("item");
            StringBuilder sql = new StringBuilder();
            sql.append("CREATE TABLE `")
                    .append(tableName)
                    .append("` (");
            for (Object item : items) {
                StringBuilder builder = new StringBuilder();
                JSONObject it = (JSONObject) item;
                String type;
                switch (it.getString("type")) {
                    case "int":
                        type = " INTEGER ";
                        break;
                    case "TIME":
                        type = " NUMERIC ";
                        break;
                    default:
                        type = " TEXT ";
                        break;
                }
                builder.append("`")
                        .append(it.getString("name"))
                        .append("`")
                        .append(type)
                        .append(it.getBoolean("isNull") ? "" : " NOT NULL ")
                        .append(it.getBoolean("isKey") ? " PRIMARY KEY AUTOINCREMENT " : "")
                        .append(",");
                sql.append(builder.toString());
            }
            sql.append(");");
            statement.execute(sql.toString().replace(",);", ");"));
            statement.closeOnCompletion();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void build(JSONObject json) {
        try {
            Class.forName("org.sqlite.JDBC");
            sql = new File("db" + File.separator + json.getString("file"));
            if (!sql.exists()) {
                createSql(json);
            } else {
                conn = DriverManager.getConnection(url + sql.getAbsolutePath());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean setDB(String fileName) {
        try {
            Class.forName("org.sqlite.JDBC");
            sql = new File("db" + File.separator + fileName);
            if (sql.exists()) {
                if (conn != null && !conn.isClosed()) {
                    conn.close();
                }
                conn = DriverManager.getConnection(url + sql.getAbsolutePath());
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static void main(String[] args) {

    }
}
