package com.xixun.xixunplayer;

import android.content.Context;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.view.Gravity;
import android.widget.Toast;

import com.aliyun.imageaudit20191230.models.ScanImageAdvanceRequest;
import com.aliyun.tea.TeaModel;

import java.io.CharArrayWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Random;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.CountDownLatch;

import gnph.util.IOs;
import gnph.util.JSMap;
import gnph.util.O;
import wseemann.media.FFmpegMediaMetadataRetriever;


public class Util {
    enum Custom{Normal, Yishi};
    public static final Custom custom = Custom.Normal;
    public static JSMap cfg;
    public static SQLiteOpenHelper openHelper;
    public static String serverURL;
    public static volatile long downId;
    public static int screenWidth = 1920, screenHeight = 1080;
    public static double lat, lng;
    public static boolean isScreenOn, logOn;

    public static void initDir(Context ctx) {
        var dir = Build.VERSION.SDK_INT < Build.VERSION_CODES.R ? Environment.getExternalStorageDirectory().getAbsolutePath() + "/XixunPlayer" : ctx.getExternalFilesDir(null).getAbsolutePath();
        Util.println("\n---- Init dir "+dir);
        Util.programDir = dir + "/program";
        Util.backImgFile = dir + "/background";

        var program = new File(Util.programDir);
        if(program.isFile()) program.delete();
        Util.println("  mkdir: "+program.mkdirs());
    }

    public static final BitmapFactory.Options noScaled = new BitmapFactory.Options();
    static {
        noScaled.inScaled = false;
    }
    public static final Vector<TCPThread> socketThreads = new Vector<>();
    public static final HashMap<Integer, String[]> stateDescs = new HashMap<>();
    static {
        stateDescs.put(1, new String[]{"Initialize", "初始化"});
        stateDescs.put(2, new String[]{"Schedules is over", "定时节目结束"});
        stateDescs.put(3, new String[]{"No programs waiting to be played", "无待播放的节目"});
        stateDescs.put(4, new String[]{"Delete program", "删除节目"});
        stateDescs.put(5, new String[]{"Program processing", "处理节目中"});
        stateDescs.put(6, new String[]{"Program Processed", "处理节目完成"});
        stateDescs.put(7, new String[]{"Program maybe error", "节目可能有误"});
        stateDescs.put(8, new String[]{"Screen-off", "关屏"});
        stateDescs.put(9, new String[]{"Program's area hasn't arrived yet", "定点节目不在范围"});
    }
    public static final String[] stateDescsUnknow = {"Unknown", "未知"};

    public static StringBuffer buf = new StringBuffer();
    public static Random rand = new Random();
    public static SimpleDateFormat dateFmt = new SimpleDateFormat("yy-MM-dd HH:mm:ss.SSS");

    public static void println(String msg) {
        System.out.println(msg);
        if(buf.length()>1000000) buf.replace(0, 100000, "");
        buf.append(msg).append("\n");
    }
    public static void printStackTrace(Throwable e) {
        println(toStackTrace(e));
    }

    public static String toStr(Throwable e) {
        var traces = e.getStackTrace();
        var msg = e.toString();
        for(var trace : traces) if(trace.getClassName().startsWith("com.xixun.xixunplayer.")) {
            msg += "\n  at "+trace.getFileName()+'.'+trace.getMethodName()+':'+trace.getLineNumber();
        }
        return msg;
    }
    public static String toStackTrace(Throwable e) {
        var out = new CharArrayWriter();
        var writer = new PrintWriter(out);
        e.printStackTrace(writer);
        writer.flush();
        return out.toString();
    }

    public static Toast makeText(Context context, CharSequence text) {
        var toast = Toast.makeText(context, text, Toast.LENGTH_LONG);
        toast.setGravity(Gravity.TOP | Gravity.LEFT, 0, 0);
        return toast;
    }

    public static String[] getState(int state) {
        var descs = stateDescs.get(state);
        return descs!=null ? descs : stateDescsUnknow;
    }

    public static String programDir, backImgFile;
    public static String getCardId() {
        try {
            var bytes = IOs.readBytesClose(new FileInputStream("/data/joey/signed/card.id"));
            if(bytes.length < 40) return "";
            byte[] cMyKey = new byte[]{97, 119, 38, 3, 46, 112, 36, 93, 58, 100, 103, 62, 115, 112, 114, 51, 43, 61, 2, 101, 119};
            for(int i=0; i<20; ++i) bytes[i] = (byte) (bytes[i * 2] - cMyKey[i] - i - (bytes[i * 2 + 1] - 3));
            var cardId = new String(bytes);
            if(cardId.length() > 13) cardId = cardId.substring(0, 13);
            return cardId;
        } catch (IOException e) {
            printStackTrace(e);
            return "";
        }
    }

    public static void deleteFiles(long proSize, Set<String> keeps) {
        var statFs = new StatFs(Environment.getExternalStorageDirectory().getPath());
        var remain = statFs.getAvailableBytes() - proSize - 400000000;
        if(remain >= 0) return;
        var latch = new CountDownLatch(1);
        MainActivity.ins.runOnUiThread(() -> {
            System.out.println("stopProg ...");
            MainActivity.ins.stopProg();
            latch.countDown();
        });
        var files = new File(Util.programDir).listFiles();
        if(files == null) return;
        Arrays.sort(files, (f1, f2) -> (int) (f1.lastModified() - f2.lastModified()));
        try {
            latch.await();
        } catch (InterruptedException ignored) {}
        for(var file : files) {
            if(keeps!=null && keeps.contains(file.getName())) continue;
            var len = file.length();
            if(file.delete()) {
                remain += len;
                if(remain>=0) break;
            }
        }
    }
    public static int caseThen(int val, int cas, int then) {
        return val==cas ? then : val;
    }

    public static com.aliyun.imageaudit20191230.Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config().setAccessKeyId("LTAI5tJh71Sz9fRM3itMm2jH").setAccessKeySecret("yujMXB95cNTpG4IUJ6eFDhZwJuHl6u");
        config.endpoint = "imageaudit.cn-shanghai.aliyuncs.com";
        return new com.aliyun.imageaudit20191230.Client(config);
    }
    public static boolean check(Prog view) {
        try {
            var client = createClient();
            var taskList = new ArrayList<ScanImageAdvanceRequest.ScanImageAdvanceRequestTask>();
            var sceneList = new ArrayList<String>();
            int idx = 0;
            for(var page : view.pages) for(var layer : page.layers) for(var src : layer.srcs) {
                if(src.typ == 'V') {
                    var retriever = new FFmpegMediaMetadataRetriever();
                    try {
                        retriever.setDataSource(src.path);
                        var dur = Long.parseLong(retriever.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_DURATION));
                        Util.println("  dur "+dur);
                        for(long i=0; i<dur; i+=10000) {
                            var frame = retriever.getFrameAtTime(i*1000, FFmpegMediaMetadataRetriever.OPTION_CLOSEST);
                            var file = Util.programDir+"/capture"+(++idx);
                            var out = new FileOutputStream(file);
                            frame.compress(Bitmap.CompressFormat.JPEG, 75, out);
                            O.close(out);
                            var in = new FileInputStream(file);
                            var task = new ScanImageAdvanceRequest.ScanImageAdvanceRequestTask();
                            task.setDataId("capture"+idx);
                            task.setImageTimeMillisecond(1L);
                            task.setInterval(1);
                            task.setMaxFrames(1);
                            task.setImageURLObject(in);
                            taskList.add(task);
                            sceneList.add("porn");
                        }
                    } finally {
                        retriever.release();
                    }
                }
            }
            var scanImageAdvanceRequest = new com.aliyun.imageaudit20191230.models.ScanImageAdvanceRequest().setTask(taskList).setScene(sceneList);
            var runtime = new com.aliyun.teautil.models.RuntimeOptions();
            try {
                var scanImageResponse = client.scanImageAdvance(scanImageAdvanceRequest, runtime);
                Util.println(com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(scanImageResponse))); // 获取整体结果
                var results = scanImageResponse.getBody().getData().results;
                for(var result : results) {
                    Util.println(" dataId "+result.dataId);
                    Util.println(" imageURL "+result.imageURL);
                    for(var subResult : result.subResults) {
                        Util.println("  suggestion "+subResult.suggestion);
                        if(! "pass".equals(subResult.suggestion)) return false;
                    }
                }
                return true;
            } catch (com.aliyun.tea.TeaException teaException) {
                Util.println(com.aliyun.teautil.Common.toJSONString(teaException)); // 获取整体报错信息
                //Util.println(teaException.getCode());// 获取单个字段
                return false;
            }
        } catch (Exception e) {
            Util.printStackTrace(e);
            return false;
        }
    }
}
