package com.xixun.xixunplayer;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.StrictMode;
import android.view.Choreographer;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.xixun.joey.aidlset.CardService;

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

import gnph.util.JSMap;

public class MainActivity extends Activity implements Choreographer.FrameCallback {

    public static MainActivity ins;
    ArrayList<ServiceConnection> services = new ArrayList<>();
    BackView backView;

    @RequiresApi(api = Build.VERSION_CODES.R)
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ins = this;
        Util.println("==>> MainActivity onCreate >>>> this "+hashCode()+" Thread: "+Thread.currentThread().getId());

        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitAll().build());
        setContentView(backView = new BackView(MainActivity.this));

        if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) init();
        else {
            Util.println("---- No permission, Try again ...");
            Util.makeText(this, "No permission, Try again ...").show();
            ActivityCompat.requestPermissions(this, new String[]{
                android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
                android.Manifest.permission.READ_EXTERNAL_STORAGE,
                android.Manifest.permission.MANAGE_EXTERNAL_STORAGE,
                android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
                android.Manifest.permission.INTERNET
            }, 999);
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(Util.programDir!=null) return;
        if(requestCode==999 && grantResults.length > 0 && grantResults[0]==PackageManager.PERMISSION_GRANTED) init();
        else {
            Util.println("---- Request Permission Failed");
            Util.makeText(this, "Request Permission Failed").show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Util.println("==<< MainActivity onDestroy <<<< this "+hashCode());
        ins = null;
        for(var service : services) unbindService(service);
        try (var fout = new FileOutputStream(Util.programDir+"/cfg")){
            Util.cfg.write(fout);
            fout.flush();
            fout.getFD().sync();
        } catch (Exception ignored) {
        }
        System.gc();
    }

    @Override
    protected void onStart() {
        super.onStart();
        Util.println("  ==>> MainActivity onStart >> "+hashCode());
    }
    @Override
    protected void onStop() {
        super.onStop();
        Util.println("  ==<< MainActivity onStop << "+hashCode());
    }
    @Override
    protected void onRestart() {
        super.onRestart();
        Util.println("  ==>> MainActivity onRestart >> "+hashCode());
    }

    @Override
    protected void onResume() {
        super.onResume();
        Util.println("  ==>> MainActivity onResume >> "+hashCode());
    }

    @Override
    protected void onPause() {
        super.onPause();
        Util.println("  ==<< MainActivity onPause << "+hashCode());
    }

    CardService serviCard;
    Intent intenCard;
    ServiceConnection connCard;
    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    public void init() {
        Util.initDir(this);
        backView.cosImg = BitmapFactory.decodeFile(Util.backImgFile, Util.noScaled);
        backView.invalidate();
        if(MainService.ins==null) startService(new Intent(this, MainService.class));

        var cfg = new File(Util.programDir+"/cfg");
        if(! cfg.isFile()) Util.cfg = new JSMap();
        else {
            try {
                Util.cfg = JSMap.fromClose(new FileInputStream(cfg));
            } catch (Exception e) {
                Util.cfg = new JSMap();
                Util.makeText(MainActivity.this, Util.toStr(e)).show();
                Util.printStackTrace(e);
            }
        }
        Util.println(Util.cfg.toStr());
        connCard = new ServiceConnection() {
            public void onServiceDisconnected(ComponentName name) {
                serviCard = null;
                Util.println("<-<- AIDL Service cardsystem Disconnected");
            }

            public void onServiceConnected(ComponentName name, IBinder iBinder) {
                unbindService(this);
                services.remove(this);
                Util.println("->-> AIDL Service cardsystem Connected");
                serviCard = CardService.Stub.asInterface(iBinder);
                try {
                    //Util.screenWidth = serviCard.getScreenWidth();
                    //Util.screenHeight = serviCard.getScreenHeight();
                    Util.println("  screen: "+Util.screenWidth+" x "+Util.screenHeight);
                    backView.invalidate();
                } catch (Exception e) {
                    Util.makeText(MainActivity.this, Util.toStr(e)).show();
                    Util.printStackTrace(e);
                }
            }
        };
        intenCard = new Intent("com.xixun.joey.aidlset.SettingsService");
        intenCard.setPackage("com.xixun.joey.cardsystem");
        bindService(intenCard, connCard, Context.BIND_AUTO_CREATE);
        services.add(connCard);
    }


    Choreographer choreographer = Choreographer.getInstance();
    boolean canAdd = true;

    @Override
    public void doFrame(long frameTimeNanos) {
        if(backView == null) {
            canAdd = true;
            return;
        }
        choreographer.postFrameCallback(this);
        canAdd = false;
        //var milli = System.currentTimeMillis();
    }
}