package com.xypower.common;

import android.content.Context;
import android.os.Environment;

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.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

public class JSONUtils {

    public static JSONObject loadJson(String path) {
        JSONObject jsonObject = null;

        FileInputStream fis = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        StringBuilder stringBuilder = null;
        try {
            File appCfgFile = new File(path);
            if (appCfgFile.exists()) {
                fis = new FileInputStream(appCfgFile);
                inputStreamReader = new InputStreamReader(fis, "UTF-8");
                bufferedReader = new BufferedReader(inputStreamReader);
                String line;
                stringBuilder = new StringBuilder();
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuilder.append(line);
                }
            }

            if (stringBuilder != null) {
                jsonObject = new JSONObject(stringBuilder.toString());
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            if (inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }

        return jsonObject;
    }


    public static byte[] loadByte(String path) {
        ByteArrayOutputStream out = null;
        byte[] outbyte = null;
        FileInputStream fis = null;
        try {
            File appCfgFile = new File(path);
            if (appCfgFile.exists()) {
                fis = new FileInputStream(appCfgFile);
                byte[] bytes = new byte[1024 * 4];
                int line = 0;
                out = new ByteArrayOutputStream();
                while ((line = fis.read(bytes)) != -1) {
                    out.write(bytes, 0, line);
//                    System.out.println("dfsdaf:" + bytes);
                }
                outbyte = out.toByteArray();
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                    out.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }

        return outbyte;
    }

    public static boolean saveByte(String path, byte[] jsonObject) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(new File(path));
            fos.write(jsonObject);
            return true;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }

        return false;
    }

    public static boolean saveJson(String path, JSONObject jsonObject) {
        FileOutputStream fos = null;
        OutputStreamWriter outputStreamWriter = null;
        try {
            fos = new FileOutputStream(new File(path));
            outputStreamWriter = new OutputStreamWriter(fos, "UTF-8");
            outputStreamWriter.write(jsonObject.toString());
            return true;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStreamWriter != null) {
                try {
                    outputStreamWriter.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }

        return false;
    }

    public static boolean updateJsonProperty(JSONObject jsonObject, String name, int fieldType, Object val) {
        if (name == null) {
            return false;
        }

        JSONArray arr;

        String[] fields = name.split("\\.");
        if (fields == null || fields.length == 0) {
            return false;
        }

        int arrayIndex = 0;
        boolean isArray = false;
        String fieldName = null;

        JSONObject node = jsonObject;
        int i = 0;

        try {
            for (; i < fields.length - 1; i++) {
                int pos = fields[i].indexOf('[');
                if (pos != -1) {
                    // Array
                    isArray = true;
                    int pos2 = fields[i].indexOf(']', pos + 1);
                    if (pos == 0 || pos2 == -1 || pos2 == (pos + 1)) {
                        return false;
                    }
                    fieldName = fields[i].substring(0, pos);
                    arrayIndex = Integer.parseInt(fields[i].substring(pos + 1, pos2 - pos - 1));

                    if (!node.has(fieldName) && val == null) {
                        return true;
                    }
                    JSONArray jsonArray = node.optJSONArray(fieldName);
                    if (jsonArray == null) {
                        jsonArray = new JSONArray();
                        node.put(fieldName, jsonArray);
                        jsonArray = node.optJSONArray(fieldName);
                    }
                    while (arrayIndex >= jsonArray.length()) {
                        jsonArray.put(new JSONObject());
                    }
                    node = jsonArray.optJSONObject(arrayIndex);
                } else {
                    if (!node.has(fields[i])) {
                        if (val == null)
                            return true;
                        else {
                            node.put(fields[i], new JSONObject());
                        }
                    }
                    node = node.optJSONObject(fields[i]);
                }
            }

            if (node == null) {
                return (val == null);
            }

            if (val == null) {
                node.remove(fields[i]);
            } else {
                node.put(fields[i], val);
            }

            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return false;
    }
}
