package com.xixun.xixunplayer;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.IBinder;
import android.os.RemoteException;

import com.xixun.command.reply.TaskProgressReply;
import com.xixun.util.PlayerInfo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashSet;

import gnph.util.IOs;
import gnph.util.JSList;
import gnph.util.JSMap;
import gnph.util.URLConn;

public class AIDLService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    PlayerInfo.Stub binder = new PlayerInfo.Stub() {
        @Override
        public String getProgramName() throws RemoteException {
            return null;
        }

        @Override
        public String getVersion() throws RemoteException {
            Util.println("Server getVersion. <-"+null);
            return null;
        }

        @Override
        public void setScreenWidth(int width) throws RemoteException {
            Util.println("Server setScreenWidth. ->"+width);
        }

        @Override
        public void setScreenHeight(int height) throws RemoteException {
            Util.println("Server setScreenHeight. ->"+height);

        }

        @Override
        public void taskScreenshot(String cmdId) throws RemoteException {
            Util.println("Server taskScreenshot. ->"+cmdId);
        }

        @Override
        public void setExternalTemperature(float t) throws RemoteException {

        }

        @Override
        public void setInternalTemperature(float t) throws RemoteException {

        }

        @Override
        public void setHumidity(float h) throws RemoteException {

        }

        @Override
        public boolean forcePlayProgram(String pid) throws RemoteException {
            return false;
        }

        @Override
        public boolean finishForcePlay() throws RemoteException {
            return false;
        }

        @Override
        public String getCurProgramId() throws RemoteException {
            Util.println("Server getCurProgramId ...");
            return null;
        }

        @Override
        public void setUSBProgramPwd(String pwd) throws RemoteException {

        }

        @SuppressLint("ResourceType")
        @Override
        public String executeJosnCommand(String jsonstr) throws RemoteException {
            Util.println("AIDL executeJsonCommand ..."+jsonstr);//{"_type":"DeleteTask","id":"652522a0e81d1e000009201a","sendTo":"yzd-player"}
            String commandId = null;
            try {
                var jsonBytes = jsonstr.getBytes(StandardCharsets.UTF_8);
                var json = JSMap.from(jsonBytes);
                var _type = json.stnn("_type");
                commandId = json.stnn("id");
                if(_type.equals("DeleteTask")) {
                    return new JSMap(
                            "_type", "DataCallback",
                            "result", "received command",
                            "cardId", Util.getCardId(),
                            "commandId", commandId
                    ).toString();
                } else if(_type.equals("SetPlayerBackground")) {
                    var url = json.str("url");
                    if(url==null) new File(Util.backImgFile).delete();
                    else {
                        var fout = new FileOutputStream(Util.backImgFile);
                        IOs.write(fout, new URLConn(url).in());
                        fout.flush();
                        fout.getFD().sync();
                        fout.close();
                    }
                    MainActivity.ins.runOnUiThread(() -> {
                        MainActivity.ins.backView.cosImg = url==null ? null : BitmapFactory.decodeFile(Util.backImgFile, Util.noScaled);
                        MainActivity.ins.backView.invalidate();
                    });
                    return new JSMap(
                            "_type", "Success",
                            "cardId", Util.getCardId(),
                            "commandId", commandId
                    ).toString();
                } else if(_type.equals("GetPlayerBackground")) {
                    var backImg = new File(Util.backImgFile);
                    var img = Base64.getEncoder().encodeToString(IOs.readBytesClose(backImg.exists() ? new FileInputStream(backImg) : MainActivity.ins.getResources().openRawResource(R.drawable.back)));
                    return new JSMap(
                            "_type", "DataCallback",
                            "cardId", Util.getCardId(),
                            "commandId", commandId,
                            "img", img
                    ).toString();
                } else if(_type.equalsIgnoreCase("getProgramTask")) {
                    var task = JSMap.fromClose(new FileInputStream(Util.programDir+"/program")).jsmap("task");
                    return new JSMap(
                            "_type", "ProgramTaskCallback",
                            "cardId", Util.getCardId(),
                            "commandId", commandId,
                            "task", task
                    ).toString();
                }
                return new JSMap(
                        "_type", "Error",
                        "errorMessage", "Unknown Type: "+_type,
                        "cardId", Util.getCardId(),
                        "commandId", commandId
                ).toString();
            } catch (Exception e) {
                Util.printStackTrace(e);
                return new JSMap(
                    "_type", "Error",
                    "errorMessage", Util.toStr(e),
                    "cardId", Util.getCardId(),
                    "commandId", commandId
                ).toString();
            }
        }

        @Override
        public void pausePlayer(boolean b) throws RemoteException {

        }

        @Override
        public boolean isPause() throws RemoteException {
            return false;
        }

        @Override
        public boolean clearTasks() throws RemoteException {
            return true;
        }

        @Override
        public int countOfPrograms(int type) throws RemoteException {
            return 0;
        }

        @Override
        public void playInsertTask(String pid) throws RemoteException {

        }

        @Override
        public void stopInsertTask(String pid) throws RemoteException {

        }

        @Override
        public String getProgramTask() throws RemoteException {
            try {
                return IOs.readStrClose(new FileInputStream(Util.programDir+"/program"));
            } catch (Exception e) {
                Util.printStackTrace(e);
                return Util.toStr(e);
            }
        }

        @Override
        public void setUploadLogUrl(String playLog) throws RemoteException {

        }

        @Override
        public String getUploadLogUrl() throws RemoteException {
            return null;
        }
    };

    static class Src {
        String filename;
        String url;

        public Src(String filename, String url) {
            this.filename = filename;
            this.url = url;
        }
    }
    static class NeedDowns {
        String prog;
        ArrayList<Src> srcs = new ArrayList<>();
    }
}