package com.xixun.xixunplayer;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.StatFs;
import android.view.Gravity;
import android.widget.Toast;

import java.io.CharArrayWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
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;

public class Util {
    public static String serverURL;
    public static int screenWidth, screenHeight;
    public static boolean isScreenOn;

    public static final BitmapFactory.Options noScaled = new BitmapFactory.Options();
    static {
        noScaled.inScaled = false;
    }
    public static final Vector<SocketThread> 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 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(new File("/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 - 1048576;
        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;
            }
        }
    }
}
