package com.xypower.mpmaster.sms;


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

import androidx.annotation.RequiresApi;

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

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;

public class UpdateSysConfigUtil {
    public static final String PACKAGE_NAME_MPAPP = "com.xypower.mpapp";
    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 leftTop = "leftTop";
    public static String rightTop = "rightTop";
    public static String leftBottom = "leftBottom";
    public static String rightBottom = "rightBottom";

    //创建运维配置文件文件夹
    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(PACKAGE_NAME_MPAPP);
        String path = appPath + "data/channels/" + channel + ".json";
        return path;
    }

    //获取配置文件地址
    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(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, HashMap<String, String> hashMap) {
        String path = getChannelDir(channel);
        JSONObject jsonObject = JSONUtils.loadJson(path);
        try {
            jsonObject.put(UpdateSysConfigUtil.leftTop, hashMap.get(UpdateSysConfigUtil.leftTop));
            jsonObject.put(UpdateSysConfigUtil.rightTop, hashMap.get(UpdateSysConfigUtil.rightTop));
            jsonObject.put(UpdateSysConfigUtil.leftBottom, hashMap.get(UpdateSysConfigUtil.leftBottom));
            jsonObject.put(UpdateSysConfigUtil.rightBottom, hashMap.get(UpdateSysConfigUtil.rightBottom));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return JSONUtils.saveJson(path, jsonObject);
    }

    //查询通道分辨率
    public static HashMap<String, String> getChannelOSD(int channel) {
        HashMap<String, String> hashMap = new HashMap<>();
        String path = getChannelDir(channel);
        JSONObject jsonObject = JSONUtils.loadJson(path);
        try {
            String leftTop = jsonObject.getString(UpdateSysConfigUtil.leftTop);
            String rightTop = jsonObject.getString(UpdateSysConfigUtil.rightTop);
            String leftBottom = jsonObject.getString(UpdateSysConfigUtil.leftBottom);
            String rightBottom = jsonObject.getString(UpdateSysConfigUtil.rightBottom);
            hashMap.put(UpdateSysConfigUtil.leftTop, leftTop);
            hashMap.put(UpdateSysConfigUtil.rightTop, rightTop);
            hashMap.put(UpdateSysConfigUtil.leftBottom, leftBottom);
            hashMap.put(UpdateSysConfigUtil.rightBottom, rightBottom);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return hashMap;
    }


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

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

        path = new File(appPath + "sentPhotos/");
        if (path.exists() && path.isDirectory()) {
            FileUtils.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()) {
            FileUtils.DeleteFilesInPath(path.getAbsolutePath());
        }

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

    }


    //重启应用
    public static void restartApp(Context context) {
        Intent intent = new Intent();
        intent.setAction(APP_ACTION_UPDATE_CONFIGS);
        intent.putExtra("restart", 1);
        context.sendBroadcast(intent);
    }

    //重启运维应用
    public static void restartMasterApp(Context context) {
        Intent intent = new Intent();
        intent.setAction(MASTER_ACTION_UPDATE_CONFIGS);
        intent.putExtra("restart", 1);
        context.sendBroadcast(intent);
    }


    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 = new byte[0];
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                decode = Base64.getDecoder().decode(msg);
            }
            if (decode != null && decode.length > 0) {
                String path = getScheduleDir(channel);
                JSONUtils.saveByte(path, decode);
            }
        }
    }


    //获取拍照时间表
    public static String getPhotoSchedules(int channel) {
        String msg = "";
        String path = getScheduleDir(channel);
        byte[] bytes = JSONUtils.loadByte(path);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            msg = Base64.getEncoder().encodeToString(bytes);
        }
        return msg;
    }
}
