package com.xixun.xixunplayer;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;

import net.lingala.zip4j.ZipFile;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;

import gnph.util.IOs;

public class MainService extends Service {

    static MainService ins;
    ArrayList<BroadcastReceiver> reces = new ArrayList<>();
    @Override
    public void onCreate() {
        super.onCreate();
        ins = this;
        Util.println("==>> MainService onCreate >>>> "+hashCode()+" Thread: "+Thread.currentThread().getId());
        TCPThread.startServer(3333);
        if(MainActivity.ins==null) {
            var intent = new Intent(this, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }

        BroadcastReceiver rece;
        var intentFilter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);
        intentFilter.addDataScheme("file");
        registerReceiver(rece = new BroadcastReceiver(){
            long lastMs;
            final char[] pass = {'8','8','8'};
            @Override
            public void onReceive(Context context, Intent intent) {  // in UI Thread
                var path = intent.getData().getPath();
                Util.println("\nMEDIA_MOUNTED path: "+path);
                var ms = System.currentTimeMillis();
                if(ms-lastMs<1000) return;
                lastMs = ms;
                Util.downId = 0;
                var acti = MainActivity.ins;
                Util.makeText(MainService.this, "MEDIA_MOUNTED path: "+path+"\nImporting 正在导入 ...").show();
                new Thread(()->{
                    try {
                        var zip = new ZipFile(path+"/program.zip");
                        if(zip.isEncrypted()) zip.setPassword(pass);
                        long size = 0;
                        ByteArrayOutputStream jsonOut = null;
                        var headers = zip.getFileHeaders();
                        for(var header : headers) {
                            size += header.getUncompressedSize();
                            if("program".equals(header.getFileName())) IOs.writeClose(jsonOut = new ByteArrayOutputStream(), zip.getInputStream(header));
                        }
                        if(jsonOut==null) {
                            Util.println("No program File");
                            if(acti!=null) acti.runOnUiThread(() -> Util.makeText(acti, "No program File").show());
                            return;
                        }
                        if(size==0) {
                            Util.println("zip size is 0");
                            if(acti!=null) acti.runOnUiThread(() -> Util.makeText(acti, "zip size is 0").show());
                            return;
                        }
                        Util.deleteFiles(size, null);
                        for(var header : headers) if(! "program".equals(header.getFileName())) {
                            Util.println("  name: " + header.getFileName());
                            var fOut = new FileOutputStream(Util.programDir + "/" + header.getFileName());
                            IOs.writeCloseIn(fOut, zip.getInputStream(header));
                            fOut.flush();
                            fOut.getFD().sync();
                            fOut.close();
                        }
                        var json = jsonOut.toByteArray();
                        Util.println("Import Succeed");
                        if(acti!=null) acti.runOnUiThread(() -> {
                            Util.makeText(acti, "Import Succeed 导入成功").show();
                            acti.initProg(json);
                        });
                        else {
                            var fOut = new FileOutputStream(Util.programDir + "/program");
                            fOut.write(json);
                            fOut.flush();
                            fOut.getFD().sync();
                            fOut.close();
                            var inten = new Intent(MainService.this, MainActivity.class);
                            inten.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(inten);
                        }
                        var inten = new Intent("com.xixun.AccessibilityService");
                        inten.putExtra("newProgram", "USB");
                        sendBroadcast(inten);
                    } catch (Exception e) {
                        Util.printStackTrace(e);
                        if(acti!=null) acti.runOnUiThread(() -> Util.makeText(acti, Util.toStr(e)).show());
                    }
                }).start();
            }
        }, intentFilter);
        reces.add(rece);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Util.println("==<< MainService onDestroy <<<< this "+hashCode());
        ins = null;
        for(var rece : reces) {
            try {
                unregisterReceiver(rece);
            } catch (Throwable ignored){
            }
        }
        System.gc();
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }
}