package com.xypower.mpmaster.sms;


import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;

import com.xypower.common.FilesUtils;
import com.xypower.common.JSONUtils;
import com.xypower.common.MicroPhotoContext;

import org.json.JSONObject;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UpdateSysConfigUtil {
    public static final String APP_ACTION_UPDATE_CONFIGS = "com.xypower.mpapp.ACT_UPD_CFG";
    private static final String MASTER_ACTION_UPDATE_CONFIGS = "com.xypower.mpmaster.ACT_UPD_CFG";

    //拍照的广播
    public static final String ACTION_TAKE_PHOTO = "com.xypower.mpapp.ACT_TP";

    public static final String EXTRA_PARAM_SCHEDULES = "Schedules";

    public static final String EXTRA_PARAM_SCHEDULE = "Schedule_";

    public static final String EXTRA_PARAM_TAKING_TIME = "TakingTime";

    public static final String EXTRA_PARAM_TIME = "Time";
    public static String osd = "osd";
    public static String leftTop = "leftTop";
    public static String rightTop = "rightTop";
    public static String leftBottom = "leftBottom";
    public static String rightBottom = "rightBottom";
    public static String FILEPATH = "filePath";
    public static String FILENAME = "fileName";

    //创建运维配置文件文件夹
    public static String buildAppDir(String packageurl) {
        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
        if (!path.endsWith(File.separator)) {
            path += File.separator;
        }

        path += packageurl + File.separator;
        File pathFile = new File(path);
        if (!pathFile.exists() && !pathFile.mkdirs()) {
            return null;
        }

        return path;
    }

    //获取配置文件地址
    public static String getChannelDir(int channel) {
        String appPath = buildAppDir(MicroPhotoContext.PACKAGE_NAME_MPAPP);
        String path = appPath + "data/channels/" + channel + ".json";
        return path;
    }


    //获取配置文件地址
    public static String getMpAppDir() {
        String appPath = buildAppDir(MicroPhotoContext.PACKAGE_NAME_MPAPP);
        String content = FilesUtils.readTextFile(appPath + "data/Master.json");
        return content;
    }

    //获取配置文件地址
    public static String getSerialNo() {
        String mSerialNo;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mSerialNo = Build.getSerial();
        } else {
            mSerialNo = Build.SERIAL;
        }
        return mSerialNo;
    }

    //获取配置文件地址
    public static String getScheduleDir(int channel) {
        String appPath = buildAppDir(MicroPhotoContext.PACKAGE_NAME_MPAPP);
        String path = appPath + "data/schedules/" + channel;
        return path;
    }

    //修改运维时间表
    public static void setAbsHeartbeats(Context context, List<Integer> list) {
        MicroPhotoContext.MasterConfig masterConfig = MicroPhotoContext.getMasterConfig(context);
        int[] array = new int[list.size()];
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                array[i] = list.get(i);
            }
        }
        masterConfig.absHeartbeats = array;
        MicroPhotoContext.saveMasterConfig(context, masterConfig);
    }

    //获取运维时间表
    public static List getAbsHeartbeats(Context context) {
        MicroPhotoContext.MasterConfig masterConfig = MicroPhotoContext.getMasterConfig(context);
        ArrayList<Integer> list = new ArrayList<>();
        int[] absHeartbeats = masterConfig.absHeartbeats;
        if (absHeartbeats != null && absHeartbeats.length > 0) {
            for (int i = 0; i < absHeartbeats.length; i++) {
                list.add(absHeartbeats[i]);
            }
        }
        return list;
    }

    //修改运维状态
    public static void setMntnMode(Context context, int mntnMode) {
        MicroPhotoContext.MasterConfig masterConfig = MicroPhotoContext.getMasterConfig(context);
        masterConfig.mntnMode = mntnMode;
        MicroPhotoContext.saveMasterConfig(context, masterConfig);
    }

    //查询运维状态
    public static int getMntnMode(Context context) {
        MicroPhotoContext.MasterConfig masterConfig = MicroPhotoContext.getMasterConfig(context);
        return masterConfig.mntnMode;
    }

    //修改运维状态
    public static void setMntnServer(Context context, String server, int port) {
        MicroPhotoContext.MasterConfig masterConfig = MicroPhotoContext.getMasterConfig(context);
        masterConfig.server = server;
        masterConfig.port = port;
        MicroPhotoContext.saveMasterConfig(context, masterConfig);
    }

    //查询运维状态
    public static String getMntnServer(Context context) {
        String server = "";
        int port;
        MicroPhotoContext.MasterConfig masterConfig = MicroPhotoContext.getMasterConfig(context);
        server = masterConfig.server;
        port = masterConfig.port;
        return server + "," + port;
    }


    //修改cmdid
    public static void setCmdid(Context context, String cmdid) {
        MicroPhotoContext.AppConfig mpAppConfig = MicroPhotoContext.getMpAppConfig(context);
        mpAppConfig.cmdid = cmdid;
        MicroPhotoContext.saveMpAppConfig(context, mpAppConfig);
    }


    //查询cmdid
    public static String getCmdid(Context context) {
        MicroPhotoContext.AppConfig mpAppConfig = MicroPhotoContext.getMpAppConfig(context);
        return mpAppConfig.cmdid;
    }

    //修改app的ip
    public static void setIP(Context context, String server, int port, int utcp, int encrypto) {
        MicroPhotoContext.AppConfig mpAppConfig = MicroPhotoContext.getMpAppConfig(context);
        mpAppConfig.server = server;
        mpAppConfig.port = port;
        if (utcp != -1) {
            mpAppConfig.networkProtocol = utcp;
        }
        if (encrypto != -1) {
            mpAppConfig.encryption = encrypto;
        }
        MicroPhotoContext.saveMpAppConfig(context, mpAppConfig);
    }


    //查询cmdid
    public static String getIP(Context context) {
        MicroPhotoContext.AppConfig mpAppConfig = MicroPhotoContext.getMpAppConfig(context);
        String server = mpAppConfig.server;
        int port = mpAppConfig.port;
        int networkProtocol = mpAppConfig.networkProtocol;
        int encryption = mpAppConfig.encryption;
        return server + "," + port + "," + networkProtocol + "," + encryption;
    }

    //修改app的心跳
    public static void setHB(Context context, int heart) {
        MicroPhotoContext.AppConfig mpAppConfig = MicroPhotoContext.getMpAppConfig(context);
        mpAppConfig.heartbeat = heart;
        MicroPhotoContext.saveMpAppConfig(context, mpAppConfig);
    }


    //获取app的心跳
    public static int getHB(Context context) {
        MicroPhotoContext.AppConfig mpAppConfig = MicroPhotoContext.getMpAppConfig(context);
        int heartbeat = mpAppConfig.heartbeat;
        return heartbeat;
    }


    //修改传输协议
    public static void setTB(Context context, int tp) {
        MicroPhotoContext.AppConfig mpAppConfig = MicroPhotoContext.getMpAppConfig(context);
        mpAppConfig.networkProtocol = tp;
        MicroPhotoContext.saveMpAppConfig(context, mpAppConfig);
    }


    //获取传输协议
    public static int getTB(Context context) {
        MicroPhotoContext.AppConfig mpAppConfig = MicroPhotoContext.getMpAppConfig(context);
        int heartbeat = mpAppConfig.networkProtocol;
        return heartbeat;
    }


    //设置传输包大小
    public static void setPackage(Context context, int tp) {
        MicroPhotoContext.AppConfig mpAppConfig = MicroPhotoContext.getMpAppConfig(context);
        mpAppConfig.packetSize = tp;
        MicroPhotoContext.saveMpAppConfig(context, mpAppConfig);
    }


    //获取传输包大小
    public static int getPackage(Context context) {
        MicroPhotoContext.AppConfig mpAppConfig = MicroPhotoContext.getMpAppConfig(context);
        int heartbeat = mpAppConfig.packetSize;
        return heartbeat;
    }

    //设置通道分辨率
    public static boolean setChannelResolution(int channel, int resolutionCX, int resolutionCY, int videoCX, int videoCY) {
        String path = getChannelDir(channel);
        JSONObject jsonObject = JSONUtils.loadJson(path);
        try {
            jsonObject.put("resolutionCX", resolutionCX);
            jsonObject.put("resolutionCY", resolutionCY);
            jsonObject.put("videoCX", videoCX);
            jsonObject.put("videoCY", videoCY);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return JSONUtils.saveJson(path, jsonObject);
    }

    //查询通道分辨率
    public static HashMap getChannelResolution(int channel) {
        HashMap<String, Integer> hashMap = new HashMap<>();
        String path = getChannelDir(channel);
        JSONObject jsonObject = JSONUtils.loadJson(path);
        try {
            int resolutionCX = jsonObject.getInt("resolutionCX");
            int resolutionCY = jsonObject.getInt("resolutionCY");
            int videoCX = jsonObject.getInt("videoCX");
            int videoCY = jsonObject.getInt("videoCY");

            hashMap.put("resolutionCX", resolutionCX);
            hashMap.put("resolutionCY", resolutionCY);
            hashMap.put("videoCX", videoCX);
            hashMap.put("videoCY", videoCY);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return hashMap;
    }

    //设置通道水印
    public static boolean setChannelOSD(int channel, JSONObject osdjsonObject) {
        String path = getChannelDir(channel);
        JSONObject jsonObject = JSONUtils.loadJson(path);
        try {
            jsonObject.put(UpdateSysConfigUtil.osd, osdjsonObject);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return JSONUtils.saveJson(path, jsonObject);
    }

    //查询通道分辨率
    public static JSONObject getChannelOSD(int channel) {
        HashMap<String, String> hashMap = new HashMap<>();
        JSONObject osdjsonObject = null;
        String path = getChannelDir(channel);
        JSONObject jsonObject = JSONUtils.loadJson(path);
        try {
            if (jsonObject != null) {
                osdjsonObject = jsonObject.getJSONObject(UpdateSysConfigUtil.osd);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return osdjsonObject;
    }


    //清除历史图片和视频
    public static void clearHistoryPic(Context context) {
        String appPath = MicroPhotoContext.buildMpAppDir(context);

        File path = new File(appPath + "photos/");
        if (path.exists() && path.isDirectory()) {
            FilesUtils.DeleteFilesInPath(path.getAbsolutePath());
        }

        path = new File(appPath + "sentPhotos/");
        if (path.exists() && path.isDirectory()) {
            FilesUtils.DeleteFilesInPath(path.getAbsolutePath());
        }

    }

    //清除日志
    public static void clearHistoryLogs(Context context) {
        String appPath = MicroPhotoContext.buildMpAppDir(context);
        String masterAppDir = MicroPhotoContext.buildMasterAppDir(context);

        File path = new File(appPath + "logs/");
        if (path.exists() && path.isDirectory()) {
            FilesUtils.DeleteFilesInPath(path.getAbsolutePath());
        }

        path = new File(masterAppDir + "logs/");
        if (path.exists() && path.isDirectory()) {
            FilesUtils.DeleteFilesInPath(path.getAbsolutePath());
        }

    }

    //重启应用
    public static void restartApp(Context context) {

        Intent intent = new Intent(MicroPhotoContext.ACTION_RESTART_MP);
        intent.putExtra("noDelay", 1);
        intent.setPackage(MicroPhotoContext.PACKAGE_NAME_MPAPP);

        context.sendBroadcast(intent);
        try {
            Thread.sleep(200);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        PackageManager packageManager = context.getPackageManager();

        intent = packageManager.getLaunchIntentForPackage(MicroPhotoContext.PACKAGE_NAME_MPAPP);
        intent.putExtra("noDelay", 1);
        // intent.putExtra("reboot", 1);
        intent.addFlags(/*Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | */Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);
    }

    //重启运维应用
    public static void restartMasterApp(Context context) {
        PackageManager packageManager = context.getPackageManager();
        Intent intent = packageManager.getLaunchIntentForPackage(MicroPhotoContext.PACKAGE_NAME_MPMASTER);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        context.startActivity(intent);

        System.exit(0);
    }

    public static void takePhotoOrVideo(Context context, long channel, long preset, boolean photoOrVideo) {
        List<Long> schedules = new ArrayList<>();
        long ts = System.currentTimeMillis() / 1000;
        long val = 0;
        val |= (channel << 16);
        val |= (preset << 8);
        val |= photoOrVideo ? 0L : 1L;

        schedules.add(Long.valueOf(val));

        Intent intent1 = new Intent();
        intent1.setAction(ACTION_TAKE_PHOTO);
        int cnt = schedules.size();
        intent1.putExtra(EXTRA_PARAM_SCHEDULES, cnt);
        for (int idx = 0; idx < cnt; idx++) {
            intent1.putExtra(EXTRA_PARAM_SCHEDULE + idx, schedules.get(idx).longValue());
        }
        intent1.putExtra(EXTRA_PARAM_TIME, 0);
        intent1.putExtra(EXTRA_PARAM_TAKING_TIME, ts);
        context.sendBroadcast(intent1);
    }


    //拍照时间表修改
    public static void setPhotoSchedules(int channel, String msg) {
        if (StringUtils.isNotEmpty(msg)) {
            byte[] decode = Base64.decode(msg, Base64.DEFAULT);
            if (decode != null && decode.length > 0) {
                String path = getScheduleDir(channel);
                FilesUtils.writeFile(path, decode);
            }
        }
    }

    //获取拍照时间表
    public static String getPhotoSchedules(int channel) {
        String msg = "";
        String path = getScheduleDir(channel);
        byte[] bytes = FilesUtils.readAllBytes(path);
        msg = Base64.encodeToString(bytes, Base64.DEFAULT);
        return msg;
    }

    public static void setCommon(Context context, String actType, ArrayList<HashMap> list, String restartType) {
        if (actType.toLowerCase().equalsIgnoreCase(SmsTypeEnum.SET.value().toLowerCase())) {
            for (int i = 0; i < list.size(); i++) {
                HashMap<String, String> hashMap = list.get(i);
                String s = (String) hashMap.get(SmsTypeEnum.CFGFILE.value());
                if (s.equalsIgnoreCase(SmsTypeEnum.APP.value())) {
                    MicroPhotoContext.AppConfig mpAppConfig = MicroPhotoContext.getMpAppConfig(context);
                    Field[] fields = mpAppConfig.getClass().getDeclaredFields();
                    for (Field field : fields) {
                        hashMap.forEach((key, value) -> {
                            if (key.equalsIgnoreCase(field.getName()) && !key.equalsIgnoreCase(SmsTypeEnum.CFGFILE.value())) {
                                if (value != null) {
                                    try {
                                        if (field.getType() == String.class) {
                                            field.set(mpAppConfig, value);
                                        } else if (field.getType() == int.class) {
                                            Integer num = StringUtils.convert2Int(value);
                                            if (num != null) {
                                                field.set(mpAppConfig, num.intValue());
                                            }
                                        }
                                    } catch (IllegalAccessException e) {
                                    }
                                }
                            }
                        });
                    }
                    MicroPhotoContext.saveMpAppConfig(context, mpAppConfig);
                } else if (s.equalsIgnoreCase(SmsTypeEnum.MASTER.value())) {
                    MicroPhotoContext.MasterConfig masterConfig = MicroPhotoContext.getMasterConfig(context);
                    Field[] fields = masterConfig.getClass().getDeclaredFields();
                    for (Field field : fields) {
                        hashMap.forEach((key, value) -> {
                            if (key.equalsIgnoreCase(field.getName()) && !key.equalsIgnoreCase(SmsTypeEnum.CFGFILE.value())) {
                                if (value != null) {
                                    try {
                                        if (field.getType() == String.class) {
                                            field.set(masterConfig, value);
                                        } else if (field.getType() == int.class) {
                                            Integer num = StringUtils.convert2Int(value);
                                            if (num != null) {
                                                field.set(masterConfig, num.intValue());
                                            }
                                        }
                                    } catch (IllegalAccessException e) {
                                    }
                                }
                            }
                        });
                    }
                    MicroPhotoContext.saveMasterConfig(context, masterConfig);
                }
            }
        } else if (actType.toLowerCase().equalsIgnoreCase(SmsTypeEnum.GET.value().toLowerCase())) {
            for (int i = 0; i < list.size(); i++) {
                HashMap<String, String> hashMap = list.get(i);
                String s = (String) hashMap.get(SmsTypeEnum.CFGFILE.value());
                if (s.equalsIgnoreCase(SmsTypeEnum.APP.value())) {
                    MicroPhotoContext.AppConfig mpAppConfig = MicroPhotoContext.getMpAppConfig(context);
                    Field[] fields = mpAppConfig.getClass().getDeclaredFields();
                    for (Field field : fields) {
                        hashMap.forEach((key, value) -> {
                            if (key.equalsIgnoreCase(field.getName()) && !key.equalsIgnoreCase(SmsTypeEnum.CFGFILE.value())) {
                                try {
                                    if (field.getType() == String.class) {
                                        value = (String) field.get(mpAppConfig);
                                    } else if (field.getType() == int.class) {
                                        Integer num = StringUtils.convert2Int(value);
                                        if (num != null) {
                                            value = (String) field.get(mpAppConfig);
                                        }
                                    }
                                } catch (IllegalAccessException e) {
                                }
                            }
                        });
                    }
                } else if (s.equalsIgnoreCase(SmsTypeEnum.MASTER.value())) {
                    MicroPhotoContext.MasterConfig masterConfig = MicroPhotoContext.getMasterConfig(context);
                    Field[] fields = masterConfig.getClass().getDeclaredFields();
                    for (Field field : fields) {
                        hashMap.forEach((key, value) -> {
                            if (key.equalsIgnoreCase(field.getName()) && !key.equalsIgnoreCase(SmsTypeEnum.CFGFILE.value())) {
                                try {
                                    if (field.getType() == String.class) {
                                        value = (String) field.get(masterConfig);
                                    } else if (field.getType() == int.class) {
                                        Integer num = StringUtils.convert2Int(value);
                                        if (num != null) {
                                            value = (String) field.get(masterConfig);
                                        }
                                    }
                                } catch (IllegalAccessException e) {
                                }
                            }
                        });
                    }
                }
            }
        } else if (actType.toLowerCase().equalsIgnoreCase(SmsTypeEnum.SETFILE.value().toLowerCase())) {
            for (int i = 0; i < list.size(); i++) {
                HashMap<String, String> hashMap = list.get(i);
                String s = (String) hashMap.get(SmsTypeEnum.CFGFILE.value());
                if (s.equalsIgnoreCase(SmsTypeEnum.APP.value())) {


                    MicroPhotoContext.AppConfig mpAppConfig = MicroPhotoContext.getMpAppConfig(context);
                    Field[] fields = mpAppConfig.getClass().getDeclaredFields();
                    for (Field field : fields) {
                        hashMap.forEach((key, value) -> {
                            if (key.equalsIgnoreCase(field.getName()) && !key.equalsIgnoreCase(SmsTypeEnum.CFGFILE.value())) {
                                if (value != null) {
                                    try {
                                        if (field.getType() == String.class) {
                                            value = (String) field.get(mpAppConfig);
                                        } else if (field.getType() == int.class) {
                                            Integer num = StringUtils.convert2Int(value);
                                            if (num != null) {
                                                value = (String) field.get(mpAppConfig);
                                            }
                                        }
                                    } catch (IllegalAccessException e) {
                                    }
                                }
                            }
                        });
                    }
                } else if (s.equalsIgnoreCase(SmsTypeEnum.MASTER.value())) {
                    MicroPhotoContext.MasterConfig masterConfig = MicroPhotoContext.getMasterConfig(context);
                    Field[] fields = masterConfig.getClass().getDeclaredFields();
                    for (Field field : fields) {
                        hashMap.forEach((key, value) -> {
                            if (key.equalsIgnoreCase(field.getName()) && !key.equalsIgnoreCase(SmsTypeEnum.CFGFILE.value())) {
                                if (value != null) {
                                    try {
                                        if (field.getType() == String.class) {
                                            value = (String) field.get(masterConfig);
                                        } else if (field.getType() == int.class) {
                                            Integer num = StringUtils.convert2Int(value);
                                            if (num != null) {
                                                value = (String) field.get(masterConfig);
                                            }
                                        }
                                    } catch (IllegalAccessException e) {
                                    }
                                }
                            }
                        });
                    }
                }
            }
        } else if (actType.toLowerCase().equalsIgnoreCase(SmsTypeEnum.GETFILE.value().toLowerCase())) {

        }

    }

}
