package com.yutou.jianr_mg.Databases;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.yutou.jianr_mg.Application;
import com.yutou.jianr_mg.Tools.Utils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JianRDataDataBase extends SQLiteOpenHelper {
    private static JianRDataDataBase database;
    private SQLiteDatabase writeDatabase, readDatabase;
    private final static String TAB_DATA_TYPE = "t_data_type";
    private final static String TAB_DATA_NAME = "t_data_name";
    private final static String TAB_DATA_GAME = "t_data_GAME";
    private final static String TAB_DATA_DROP = "t_data_DROP";

    public static JianRDataDataBase init() {
        if (database == null) {
            database = new JianRDataDataBase();
            database.readDatabase = database.getReadableDatabase();
            database.writeDatabase = database.getWritableDatabase();
        }
        return database;
    }

    private JianRDataDataBase() {
        super(Application.application, "game_data_db", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        /*
         *    ---------------------------------------------------
         *    |     标题      |       类型      |       说明      |
         *    ---------------------------------------------------
         *    |     _id      |        int      |      id自增     |
         *    ---------------------------------------------------
         *    |   typeName   |    varchar(255) |     分类名字    |
         *    ---------------------------------------------------
         */
        String sql = "create table " + TAB_DATA_TYPE + " (_id integer primary key,typeName varchar(255))";
        /*
         *    ---------------------------------------------------
         *    |     标题      |       类型      |       说明      |
         *    ---------------------------------------------------
         *    |     _id      |        int      |      id自增     |
         *    ---------------------------------------------------
         *    |    typeId    |        int      |     分类id      |
         *    ---------------------------------------------------
         *    |   title      |    varchar(255) |     数据库名     |
         *    ---------------------------------------------------
         */
        String sql_2 = "create table " + TAB_DATA_NAME + " (_id integer primary key,typeId integer,title varchar(255))";
        /*
         *    ---------------------------------------------------
         *    |     标题      |       类型      |       说明      |
         *    ---------------------------------------------------
         *    |     _id      |        int      |      id自增     |
         *    ---------------------------------------------------
         *    |    nameId    |        int      |     数据id      |
         *    ---------------------------------------------------
         *    |     mapId    |    varchar(255) |     地图编号     |
         *    ---------------------------------------------------
         *    |  nodeType    |    varchar(255) |    节点类型      |
         *    ---------------------------------------------------
         *    |   litter     |    varchar(20)  |    凋落物cid     |
         *    ---------------------------------------------------
         *    |     src      |       text      |     原始数据     |
         *    ---------------------------------------------------
         *    |      m,a     |    varchar(50)  |  用于关联战斗信息 |
         *    ---------------------------------------------------
         *    |  createTime  |    varchar(255) |    创建时间      |
         *    ---------------------------------------------------
         *    |     md5      |    varchar(255) |   md5校验唯一性  |
         *    ---------------------------------------------------
         */
        String sql_3 = "create table " + TAB_DATA_GAME + " (_id integer primary key,nameId integer,mapId varchar(255),nodeType varchar(20),litter varchar(255),src text,m varchar(50),a vharchar(50),createTime varchar(255),md5 varchar(255))";


        /*
         *    ---------------------------------------------------
         *    |     标题      |       类型      |       说明      |
         *    ---------------------------------------------------
         *    |     _id      |        int      |      id自增     |
         *    ---------------------------------------------------
         *    |     dataId   |        int      |      数据id     |
         *    ---------------------------------------------------
         *    |     cid      |   varchar(255)  |     舰娘CID     |
         *    ---------------------------------------------------
         *    |     title    |   varchar(255)  |     舰娘名字     |
         *    ---------------------------------------------------
         *    |     md5      |   varchar(255)  |     防止重复     |
         *    ---------------------------------------------------
         */
        String sql_4="create table " + TAB_DATA_DROP + " (_id integer primary key,dataId integer,cid varchar(255), title varchar(255),md5 varchar(255))";
        sqLiteDatabase.execSQL(sql);
        sqLiteDatabase.execSQL(sql_2);
        sqLiteDatabase.execSQL(sql_3);
        sqLiteDatabase.execSQL(sql_4);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
    public void addDrop(JSONObject json){
        if(!queryGameDrop(Utils.getMD5(json.toString()+"Drop"))){
            try{
                JSONArray newShipVO=new JSONObject(json.getString("message")).getJSONArray("newShipVO");
                if(newShipVO!=null&&newShipVO.length()>0){
                    String cid=newShipVO.getJSONObject(0).get("shipCid").toString();
                    String title=newShipVO.getJSONObject(0).getString("title");
                    ContentValues values=new ContentValues();
                    values.put("dataId",json.getInt("dataId"));
                    values.put("cid",cid);
                    values.put("title",title);
                    values.put("md5",Utils.getMD5(json.toString()+"Drop"));
                    readDatabase.insert(TAB_DATA_DROP,null,values);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
    public List<JSONObject> getDrops(){
        List<JSONObject> list=new ArrayList<>();
        try{
            Cursor cursor=readDatabase.query(TAB_DATA_DROP,new String[]{"*"},null,null,null,null,null);
            while (cursor.moveToNext()){
                JSONObject json=new JSONObject();
                json.put("dataId",cursor.getInt(cursor.getColumnIndex("dataId")));
                json.put("cid",cursor.getString(cursor.getColumnIndex("cid")));
                json.put("title",cursor.getString(cursor.getColumnIndex("title")));
                json.put("id",cursor.getInt(cursor.getColumnIndex("_id")));
                list.add(json);
            }
            cursor.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }
    public List<JSONObject> getDrops(String name){
        List<JSONObject> list=new ArrayList<>();
        int nameId=getNameId(name);
        if(nameId<=0){
            return list;
        }

        try{
           List<JSONObject> data=getDrops();
            for (JSONObject datum : data) {
                int dataId=datum.getInt("dataId");
                JSONObject tmp=getData(dataId).get("data");
                int dId=tmp.getInt("id");
                if(datum.getInt("dataId")==dId&&nameId==tmp.getInt("nameId")){
                    datum.put("data",tmp);
                    list.add(datum);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }
    private boolean queryDataType(String title) {
        Cursor cursor = readDatabase.query(TAB_DATA_TYPE, new String[]{"*"}, "typeName=?", new String[]{title}, null, null, null);
        int count = cursor.getCount();
        cursor.close();
        return count > 0;
    }

    private boolean queryDataName(String title) {
        Cursor cursor = readDatabase.query(TAB_DATA_NAME, new String[]{"*"}, "title=?", new String[]{title}, null, null, null);
        int count = cursor.getCount();
        cursor.close();
        return count > 0;
    }

    public void addType(String title) {
        if (!queryDataType(title)) {
            ContentValues values = new ContentValues();
            values.put("typeName", title);
            writeDatabase.insert(TAB_DATA_TYPE, null, values);
        }
    }

    public void addName(String title, String context) {
        if (queryDataType(title) && getTypeId(title) != -1) {
            ContentValues values = new ContentValues();
            values.put("title", context);
            values.put("typeId", getTypeId(title));
            writeDatabase.insert(TAB_DATA_NAME, null, values);
        }
    }
    public int getTNameId(String name){
        Cursor cursor=readDatabase.query(TAB_DATA_NAME,new String[]{"*"},"title=?",new String[]{name},null,null,null);
        if(cursor.moveToNext()){
            return cursor.getInt(cursor.getColumnIndex("_id"));
        }
        return -1;
    }
    public long addData(String title, JSONObject data) {
        if (queryDataName(title) && !queryGameData(Utils.getMD5(data.toString()))) {
            try {
                JSONObject ext=new JSONObject(data.getString("ext"));
                JSONObject message=new JSONObject(data.getString("message"));
                String type=data.getString("type");
                ContentValues values = new ContentValues();
                values.put("nameId", getNameId(title));
                values.put("mapId", ext.getString("n"));
                values.put("nodeType", type);
                String cid="";
                try{
                    cid=message.getJSONArray("newShipVO").getJSONObject(0).getString("shipCid");
                }catch (Exception ignored){

                }
                values.put("litter",cid);
                values.put("m",ext.getString("m"));
                values.put("a",ext.getString("a"));
                values.put("src", data.toString());
                values.put("createTime", System.currentTimeMillis() + "");
                values.put("md5", Utils.getMD5(data.toString()));
                return writeDatabase.insert(TAB_DATA_GAME, null, values);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return -1;
    }
    public List<Map<String,JSONObject>> getDataList(){
        List<Map<String,JSONObject>> list=new ArrayList<>();
        try{
            Cursor cursor=readDatabase.query(TAB_DATA_GAME,new String[]{"*"},"nodeType=?",new String[]{"DealNode"},null,null,"_id desc");
            while (cursor.moveToNext()){
                Map<String,JSONObject> map=new HashMap<>();
                String m=cursor.getString(cursor.getColumnIndex("m"));
                String a=cursor.getString(cursor.getColumnIndex("a"));
                String n=cursor.getString(cursor.getColumnIndex("mapId"));
                JSONObject node=new JSONObject(cursor.getString(cursor.getColumnIndex("src")));
                node.put("_id",cursor.getInt(cursor.getColumnIndex("id")));
                node.put("time",cursor.getString(cursor.getColumnIndex("createTime")));
                node.put("type",cursor.getString(cursor.getColumnIndex("nodeType")));
                map.put("DealNode",node);
                map.put("GetWarResult",getWarResult(m,n,a));
                JSONObject j=new JSONObject();
                j.put("mapId",n);
                map.put("data",j);
                list.add(map);
            }
            cursor.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }
    public List<Map<String,JSONObject>> getDataList(int id){
        List<Map<String,JSONObject>> list=new ArrayList<>();
        try{
            Cursor cursor=readDatabase.rawQuery("select * from t_data_GAME game,t_data_name name,t_data_type type where name._id=? and type._id=name.typeId and game.nameId=name._id order by _id desc",new String[]{id+""});
            while (cursor.moveToNext()){
                Map<String,JSONObject> map=new HashMap<>();
                String m=cursor.getString(cursor.getColumnIndex("m"));
                String a=cursor.getString(cursor.getColumnIndex("a"));
                String n=cursor.getString(cursor.getColumnIndex("mapId"));
                JSONObject node=new JSONObject(cursor.getString(cursor.getColumnIndex("src")));
                node.put("_id",id);
                node.put("time",cursor.getString(cursor.getColumnIndex("createTime")));
                node.put("type",cursor.getString(cursor.getColumnIndex("nodeType")));
                map.put("DealNode",node);
                map.put("GetWarResult",getWarResult(m,n,a));
                JSONObject j=new JSONObject();
                j.put("mapId",n);
                map.put("data",j);
                list.add(map);
            }
            cursor.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }
    public Map<String,JSONObject> getData(int id){
        Map<String,JSONObject> map=new HashMap<>();
        try{
            Cursor cursor=readDatabase.query(TAB_DATA_GAME,new String[]{"*"},"_id=?",new String[]{id+""},null,null,null);
            if(cursor.moveToNext()){
                String m=cursor.getString(cursor.getColumnIndex("m"));
                String a=cursor.getString(cursor.getColumnIndex("a"));
                String n=cursor.getString(cursor.getColumnIndex("mapId"));
                JSONObject node=new JSONObject(cursor.getString(cursor.getColumnIndex("src")));
                node.put("_id",id);
                node.put("time",cursor.getString(cursor.getColumnIndex("createTime")));
                map.put("DealNode",node);
                map.put("GetWarResult",getWarResult(m,n,a));
                node.put("type",cursor.getString(cursor.getColumnIndex("nodeType")));
                JSONObject data=new JSONObject();
                data.put("id",cursor.getInt(cursor.getColumnIndex("_id")));
                data.put("nameId",cursor.getInt(cursor.getColumnIndex("nameId")));
                data.put("mapId",cursor.getString(cursor.getColumnIndex("mapId")));
                data.put("nodeType",cursor.getString(cursor.getColumnIndex("nodeType")));
                data.put("litter",cursor.getString(cursor.getColumnIndex("litter")));
                data.put("createTime",cursor.getString(cursor.getColumnIndex("createTime")));
                data.put("md5",cursor.getString(cursor.getColumnIndex("md5")));
                map.put("data",data);
            }
            cursor.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return map;
    }
    private JSONObject getWarResult(String m,String n,String a){
        JSONObject json=null;
        try{
            Cursor cursor=readDatabase.query(TAB_DATA_GAME,new String[]{"*"},"mapId=? and m=? and a=?",new String[]{n,m,a},null,null,null);
            cursor.moveToNext();
            if(cursor.moveToNext()){
                json=new JSONObject(cursor.getString(cursor.getColumnIndex("src")));
            }
            cursor.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return json;
    }
    private boolean queryGameData(String md5) {
        Cursor cursor = readDatabase.query(TAB_DATA_GAME, new String[]{"*"}, "md5=?", new String[]{md5}, null, null, null);
        int count = cursor.getCount();
        cursor.close();
        return count > 0;
    }
    private boolean queryGameDrop(String md5) {
        Cursor cursor = readDatabase.query(TAB_DATA_DROP, new String[]{"*"}, "md5=?", new String[]{md5}, null, null, null);
        int count = cursor.getCount();
        cursor.close();
        return count > 0;
    }
    public List<String> getTypes() {
        List<String> list = new ArrayList<>();
        Cursor cursor = readDatabase.query(TAB_DATA_TYPE, new String[]{"*"}, null, null, null, null, null);
        while (cursor.moveToNext()) {
            list.add(cursor.getString(cursor.getColumnIndex("typeName")));
        }
        cursor.close();
        return list;
    }

    public List<String> getNames(String name) {
        List<String> list = new ArrayList<>();
        if (name == null) {
            return list;
        }
        Cursor cursor = readDatabase.query(TAB_DATA_NAME, new String[]{"*"}, "typeId=?", new String[]{getTypeId(name) + ""}, null, null, null);
        while (cursor.moveToNext()) {
            list.add(cursor.getString(cursor.getColumnIndex("title")));
        }
        cursor.close();
        return list;
    }

    private int getNameId(String title) {
        int list = -1;
        Cursor cursor = readDatabase.query(TAB_DATA_NAME, new String[]{"*"}, "title=?", new String[]{title}, null, null, null);
        if (cursor.getCount() > 0) {
            cursor.moveToNext();
            list = cursor.getInt(cursor.getColumnIndex("_id"));
        }
        cursor.close();
        return list;
    }

    private int getTypeId(String title) {
        int list = -1;
        Cursor cursor = readDatabase.query(TAB_DATA_TYPE, new String[]{"*"}, "typeName=?", new String[]{title}, null, null, null);
        if (cursor.getCount() > 0) {
            cursor.moveToNext();
            list = cursor.getInt(cursor.getColumnIndex("_id"));
        }
        cursor.close();
        return list;
    }

    private void removeData(String name) {
        writeDatabase.delete(TAB_DATA_GAME, "nameId=?", new String[]{getNameId(name) + ""});
    }

    public void removeName(String name) {
        removeData(name);
        writeDatabase.delete(TAB_DATA_NAME, "title=?", new String[]{name});

    }

    public void removeType(String name) {
        removeName(name);
        writeDatabase.delete(TAB_DATA_TYPE, "typeName=?", new String[]{name});
    }
    public void clearTable(String tabName){
        writeDatabase.execSQL("delete from  "+tabName);
    }
}
