package com.yutou.jianr_mg.Tools;

import android.content.Context;
import android.content.SharedPreferences;

import com.alibaba.fastjson.JSON;
import com.yutou.jianr_mg.Application;
import com.yutou.jianr_mg.Data.AppData;
import com.yutou.jianr_mg.Data.JianNiang;
import com.yutou.jianr_mg.Data.ShipEquipmnt;
import com.yutou.jianr_mg.Data.TeamData;
import com.yutou.jianr_mg.Data.ZsShipType;
import com.yutou.jianr_mg.Interfaces.DownloadFileInerface;
import com.yutou.jianr_mg.Interfaces.HttpInterface;
import com.yutou.jianr_mg.Network.HttpApi;
import com.yutou.jianr_mg.Network.HttpUtils;

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

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class JianRUtils {
    private static JSONArray shipCardId;
    private static List<ZsShipType> types;

    public static int jianCidToid(String cid) {
        if (cid.substring(1, 2).equals("1")) {
            int con = Integer.valueOf(cid.substring(2, cid.length() - 2));
            return 1000 + con;
        } else {
            return Integer.valueOf(cid.substring(2, cid.length() - 2));
        }
    }

    public static int equipCidToid(String cid) {
        return Integer.valueOf(cid.substring(2)) / 100;
    }

    public static int EnemyShipCardId(String cid) {
        try {
            for (int i = 0; i < shipCardId.length(); i++) {
                JSONObject json = shipCardId.getJSONObject(i);
                if (json.getString("cid").equals(cid)) {
                    return json.getInt("picId");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static void initShipCardId() {
        try {
            File file = new File(Application.application.getFilesDir() + "/shipCardid");
            InputStream inputStream;
            if (!file.exists()) {
                inputStream = Application.application.getAssets().open("shipCardId");
            } else {
                inputStream = new FileInputStream(file);
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder str = new StringBuilder();
            String tmp;
            while ((tmp = reader.readLine()) != null) {
                str.append(tmp);
            }
            reader.close();
            inputStream.close();
            shipCardId = new JSONArray(str.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static List<TeamData> getUserTeam(JSONObject json) {
        List<TeamData> data = new ArrayList<>();
        try {
            JSONObject warRepoot = json.getJSONObject("warReport");
            JSONArray selfShips = warRepoot.getJSONArray("selfShips");
            for (int i = 0; i < selfShips.length(); i++) {
                TeamData team = new TeamData();
                JSONObject js = selfShips.getJSONObject(i);
                team.setId(i);
                team.setHpMax(js.get("hpMax").toString());
                team.setTitle(js.getString("title"));
                team.setJid(js.getInt("id"));
                team.setHp(warRepoot.getJSONArray("hpBeforeNightWarSelf").get(i).toString());
                team.setImageUrl("http://jianr.jianrmod.cn/jianr/ship/S_NORMAL_" + JianRUtils.jianCidToid(js.get("shipCid").toString()) + ".png");
                team.setType(js.getInt("type"));
                JSONArray array = js.getJSONArray("equipment");
                List<String> list = new ArrayList<>();
                for (int j = 0; j < array.length(); j++) {
                    list.add(array.getString(j));
                }
                team.setEquipments(list);
                try {
                    team.setItem1Url("http://jianr.jianrmod.cn/jianr/equipment/equip_L_" + JianRUtils.equipCidToid(array.get(0).toString()) + ".png");
                    team.setItem2Url("http://jianr.jianrmod.cn/jianr/equipment/equip_L_" + JianRUtils.equipCidToid(array.get(1).toString()) + ".png");
                    team.setItem3Url("http://jianr.jianrmod.cn/jianr/equipment/equip_L_" + JianRUtils.equipCidToid(array.get(2).toString()) + ".png");
                    team.setItem4Url("http://jianr.jianrmod.cn/jianr/equipment/equip_L_" + JianRUtils.equipCidToid(array.get(3).toString()) + ".png");
                } catch (Exception ignored) {

                }

                team.setUser(true);
                team.setSrc(json);
                data.add(team);
            }
            return data;
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("!!!!!--->"+json.toString());
        }
        return data;
    }

    public static List<TeamData> getNightUserTeam(JSONObject json) {
        List<TeamData> data = getUserTeam(json);
        System.out.println("用户数量：" + data.size());
        try {
            JSONObject warRepoot = json.getJSONObject("warResult");
            JSONArray selfShips = warRepoot.getJSONArray("selfShipResults");
            for (int i = 0; i < selfShips.length(); i++) {
                JSONObject js = selfShips.getJSONObject(i);
                TeamData ut = data.get(i);
                ut.setHp(js.getInt("hp") + "");
                data.set(i, ut);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }

    public static List<TeamData> getNightEnemyTeam(JSONObject json) {
        List<TeamData> data = getEnemyTeam(json);
        try {
            JSONObject warRepoot = json.getJSONObject("warResult");
            JSONArray selfShips = warRepoot.getJSONArray("enemyShipResults");
            System.out.println("血量参数：" + selfShips.length());
            for (int i = 0; i < selfShips.length(); i++) {
                JSONObject js = selfShips.getJSONObject(i);
                System.out.println("敌方血量：" + js.getInt("hp"));
                System.out.println("敌方数量：" + data.size());
                TeamData ut = data.get(i);
                ut.setHp(js.getInt("hp") + "");
                data.set(i, ut);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }

    public static List<TeamData> getEnemyTeam(JSONObject json) {
        List<TeamData> data = new ArrayList<>();
        try {
            JSONObject warRepoot = json.getJSONObject("warReport");
            JSONArray selfShips = warRepoot.getJSONArray("enemyShips");
            for (int i = 0; i < selfShips.length(); i++) {
                TeamData team = new TeamData();
                JSONObject js = selfShips.getJSONObject(i);
                team.setId(i);
                team.setHpMax(js.get("hpMax").toString());
                team.setTitle(js.getString("title"));
                team.setHp(warRepoot.getJSONArray("hpBeforeNightWarEnemy").get(i).toString());
                team.setImageUrl("http://jianr.jianrmod.cn/jianr/ship/S_NORMAL_" + JianRUtils.EnemyShipCardId(js.get("shipCid").toString()) + ".png");
                team.setUser(false);
                team.setSrc(json);
                data.add(team);
            }
            return data;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }

    public static String getShipImageByCid(int cid,boolean ship){
        if(ship)
        return "http://jianr.jianrmod.cn/jianr/ship/S_NORMAL_"+jianCidToid(cid+"")+".png";
        else{
            return "http://jianr.jianrmod.cn/jianr/equipment/equip_L_"+equipCidToid(cid+"")+".png";
        }
    }

    private static List<JianNiang> jianNiangs=new ArrayList<>();
    private static List<ShipEquipmnt> equipmnts=new ArrayList<>();

    public static void reloadJianNiang() {
        try {
            if (jianNiangs == null||jianNiangs.size()==0) {
                jianNiangs = new ArrayList<>();
                JSONArray array = new JSONArray(Utils.readFile(Utils.getAppPath() + "/jdata/shipCardWu.json"));
                for (int i = 0; i < array.length(); i++) {
                    JSONObject json = array.getJSONObject(i);
                    JianNiang jianNiang = JSON.parseObject(json.toString(), JianNiang.class);
                    jianNiangs.add(jianNiang);
                }
                System.out.println("缓存舰娘数：" + jianNiangs.size());
            }
        } catch (Exception e) {
            e.printStackTrace();
            getInit();
        }
    }
    public static void reloadShipType(){
        if(types==null){
            types=new ArrayList<>();
        }else{
            types.clear();
        }
        HttpUtils.get(HttpApi.HOME_URL + HttpApi.SHIP_TYPE, new HttpInterface() {
            @Override
            public void httpGetData(String string, int code) {
                try {
                    JSONObject json=new JSONObject(string);
                    JSONArray data=json.getJSONArray("data");
                    for (int i = 0; i < data.length(); i++) {
                        types.add(JSON.parseObject(data.getJSONObject(i).toString(),ZsShipType.class));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void httpError(Exception e) {
                e.printStackTrace();
            }
        });
    }

    public static ZsShipType getShipTypeById(int id){
        for (ZsShipType type : types) {
            if(type.getId()==id){
                return type;
            }
        }
        return null;
    }

    public static JianNiang getJianNiangByCId(int cid){
        for (JianNiang jianNiang : jianNiangs) {
            if(jianNiang.getCid()==cid){
                return jianNiang;
            }
        }
        return null;
    }

    public static List<ShipEquipmnt> reloadEquipmnts() {
        try {
            if (equipmnts == null||equipmnts.size()==0) {
                equipmnts = new ArrayList<>();
                JSONArray array = new JSONArray(Utils.readFile(Utils.getAppPath() + "/jdata/shipEquipmnt.json"));
                for (int i = 0; i < array.length(); i++) {
                    JSONObject json = array.getJSONObject(i);
                    ShipEquipmnt jianNiang = JSON.parseObject(json.toString(), ShipEquipmnt.class);
                    equipmnts.add(jianNiang);
                }
                System.out.println("缓存装备数：" + equipmnts.size());
            }
        } catch (Exception e) {
            e.printStackTrace();
            getInit();
        }
        return equipmnts;
    }

    public static ShipEquipmnt getEquipmnt(int cid, int type) {
        try {
            List<ShipEquipmnt> equipmnts = reloadEquipmnts();
            for (ShipEquipmnt equipmnt : equipmnts) {
                if (equipmnt.getCid() == cid) {
                    return equipmnt;
                }
                if (equipmnt.getType() == type) {
                    return equipmnt;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void getInit() {
        File file = new File(Utils.getAppPath() + "/getInitConfigs");
        try {
            InputStream inputStream = new FileInputStream(file);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
            }
            outputStream.flush();
            outputStream.close();
            inputStream.close();
            JSONObject init = new JSONObject(outputStream.toString());
            Utils.writerFile(Utils.getAppPath() + "/jdata/shipCardWu.json", init.getJSONArray("shipCardWu").toString());
            Utils.writerFile(Utils.getAppPath() + "/jdata/shipEquipmnt.json", init.getJSONArray("shipEquipmnt").toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void downlaodInit(boolean flag) {
        if (flag) {
            if (new File(Utils.getAppPath() + "/getInitConfigs").exists()) {
                return;
            }
        }
        HttpUtils.downloadFile("http://version.jr.moepoint.tw/index/getInitConfigs", Utils.getAppPath() + "/", new DownloadFileInerface() {
            @Override
            public boolean downloading(String fileName, int current, long length) {
                return true;
            }

            @Override
            public void over(boolean isOver) {
                new Thread(() -> {
                    JianRUtils.reloadJianNiang();
                    JianRUtils.reloadEquipmnts();
                }).start();
            }
        });
    }

    public static void readClientVersionIsbigzhao(Context context) {
        SharedPreferences sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
        AppData.magicPackageName = sp.getString("magicVersion", "com.bigzhao.jianrmagicbox");
    }

    public static boolean readClientVersion(Context context) {
        SharedPreferences sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
        return sp.getString("magicVersion", "com.bigzhao.jianrmagicbox").equals("com.bigzhao.jianrmagicbox");
    }
    public static void changeClientVersion(boolean b,Context context) {
        SharedPreferences sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
        if(b){
            sp.edit().putString("magicVersion","com.huanmeng.zhanjian2").apply();
            AppData.magicPackageName="com.huanmeng.zhanjian2";
        }else{
            sp.edit().putString("magicVersion","com.bigzhao.jianrmagicbox").apply();
            AppData.magicPackageName="com.bigzhao.jianrmagicbox";
        }

    }
}
