package com.mq.mylibrary;

import android.content.Context;
import android.content.res.AssetManager;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment;
import android.util.Log;


import com.mq.mylibrary.tool.LogTool;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * 创建人 mQ
 * 创建时间 2019/1/7 0007 14:05
 * 文件名称 MyDatabaseHelper
 * 说明:  数据库类
 **/
public class MyDatabaseHelper extends SQLiteOpenHelper {

    public static final String FILE_DIR = Environment.getExternalStorageDirectory().getAbsolutePath() + "/sjlsxxgl/";
    public static final int DATABASE_VERSION = 3;

    private static final String CREATE_SQL_FILE_NAME = "createSql.sql";

    private Context mContext;

    public MyDatabaseHelper(Context context, String name) {
        super(context, name, null, DATABASE_VERSION);
        mContext = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
//        File dir = new File(FILE_DIR);
//        if (!dir.exists()) {
//            dir.mkdir();
//        }

        List<String> createSqls = getCreateSqlInfo(CREATE_SQL_FILE_NAME);
        if (createSqls != null) {
            for (String sql : createSqls) {
                db.execSQL(sql);
                LogTool.i("onCreate创建数据表: " + sql);
            }
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        int version = oldVersion;
        if (version == 1) {
            LogTool.i("数据库版本:" + version + ", 无升级信息");
            version = 2;
        }
        if (version == 2) {
            LogTool.i("数据库版本:" + version + ", 无升级信息");
            version = 3;
        }
        if (version == 3) {
            // `back_impurity` varchar(2000) DEFAULT NULL COMMENT '是否回杂',
            // `stop_reasons` varchar(2000) DEFAULT NULL COMMENT '终止原因'
            try {
                db.execSQL("ALTER TABLE zhicang_info ADD `back_impurity` VARCHAR (2000)");
            } catch (Exception e) {}
            try {
                db.execSQL("ALTER TABLE zhicang_info ADD `stop_reasons` VARCHAR (2000)");
            } catch (Exception e) {}

            LogTool.i("数据库版本:" + version + ", 增加back_impurity,stop_reasons字段");
            version = 4;
        }
    }

    /**
     * 读取assets文件夹中的建表语句
     */
    private List<String> getCreateSqlInfo(String fileName) {
        AssetManager assetManager = mContext.getAssets();
        try {
            InputStreamReader isr = new InputStreamReader(assetManager.open(fileName));
            BufferedReader br = new BufferedReader(isr);
            String line;
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = br.readLine()) != null) {
                stringBuilder.append(line);
            }
            br.close();
            isr.close();
            LogTool.i("getCreateSqlInfo 读取建表语句: " + stringBuilder.toString());
            return parseSql(stringBuilder.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private List<String> parseSql(String sql) {
        List<String> list = new ArrayList<>();
        String[] split = sql.split(";");
        for (String s : split) {
            if (s.contains("(")) {
                String tableS;

                if (s.contains("ENGINE")) {
                    tableS = s.split("ENGINE")[0];
                } else
                    tableS = s;
                if (tableS.contains("COMMENT")) {
                    String[] items = tableS.split(",");
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < items.length; i++) {
                        String item = items[i].trim();
                        String comment = item.split("COMMENT")[0];
                        if (i == items.length - 1)
                            sb.append(comment + ")");
                        else
                            sb.append(comment + ",");
                    }
                    tableS = sb.toString();
                }
                list.add(tableS);
            }
        }
        return list;
    }
}
