package com.tcl.customerapi;

import android.app.Instrumentation;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.AssetManager;
import android.graphics.Rect;
import android.media.AudioManager;
import android.os.IBinder;
import android.os.IRtcService;
import android.os.RecoverySystem;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.SystemClock;
import android.os.SystemProperties;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.util.Log;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;

import com.tcl.appassistsdk.appupdate.AppUpdateManager;
import com.tcl.deviceinfo.TDeviceInfo;
import com.tcl.factory.FactoryManager;
import com.tcl.factory.bsp.TCL;
import com.tcl.factory.bsp.TV;
import com.tcl.factory.bsp.TVDefine;
import com.tcl.factory.def.DEFS;
import com.tcl.factory.thirdparty.ThirdParty;
import com.tcl.factory.utils.AHDeviceHelper;
import com.tcl.factory.utils.GpioHelper;
import com.tcl.factory.utils.HDMICecHelper;
import com.tcl.factory.utils.LedHelper;
import com.tcl.factory.utils.RtcTimeHelper;
import com.tcl.os.system.WindowManager;
import com.tcl.snack.content.MyPackageManager;
import com.tcl.tvmanager.TTvCecManager;
import com.tcl.tvmanager.TTvChannelManager;
import com.tcl.tvmanager.TTvFunctionManager;
import com.tcl.tvmanager.TTvPictureManager;
import com.tcl.tvmanager.TvManager;
import com.tcl.tvmanager.vo.CecConfigInfo;
import com.tcl.tvmanager.vo.EnTCLAspectRatio;
import com.tcl.tvmanager.vo.EnTCLAudioDeviceType;
import com.tcl.tvmanager.vo.EnTCLChanelListType;
import com.tcl.tvmanager.vo.EnTCLInputSource;
import com.tcl.tvmanager.vo.EnTCLMemberServiceType;
import com.tcl.tvmanager.vo.EnTCLPowerOffType;
import com.tcl.tvmanager.vo.EnTCLWindow;
import com.tcl.tvmanager.vo.ProgramInfo;
import com.tcl.tvmanager.vo.VideoWindowRect;

import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.TimeZone;

import tvos.tv.TInputSourceClient;
import tvos.tv.picture.TPictureManager;
import tvos.tv.sound.TSoundManager;

import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;

public class IService extends android.app.Service {
    private final static String TAG = "api";
    public Context ctx;
    private MyIBinder myIBinder = new MyIBinder();
    public static final String dataPath = "com.tcl.customerapi_preferences";
    public static int MODE = Context.MODE_PRIVATE;
    public HotelAPI especiallyApi;
    private LauncherHelper mLauncherHelper;
    private TInputSourceClient client;
    public TTvChannelManager channelManager;//channel list

    public MyPackageManager packageManager;
    public RtcTimeHelper rtcTimeHelper;
    public HDMICecHelper hdmiCecHelper;
    private GpioHelper mGpioHelper;
    private LedHelper mLedHelper;
    // The flags that are set for all calls we make to the package manager.
    static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "service  onCreate  !");
        ctx = this;

        if (mTvCecManager == null) {
            mTvCecManager = TTvCecManager.getInstance(ctx);
        }

        if (channelManager == null) {//channel list
            channelManager = TTvChannelManager.getInstance(this);
        }
        mLauncherHelper = new LauncherHelper(this);
        TCL.implemetThirdPartyIsntance(this);
        especiallyApi = new HotelAPI(this);
        String TSA_KEY = "U0lUQTAwMTk5OTkyMDIwMDMwMlRDTHxjb20udGNsLmN1c3RvbWVyYXBpfDMyfDB8VENMI24zOEFscGp6enJGUkpQR2hCNWhQUXZqRzVRWm1SRzllbzloelFPaFdCVFVaRVpFcUlkRTlNSC9RQ0Z5bE5Cb0NScGFmT2VGcXNPSlJsRjEyNFZZOEJraG1jb09nWmVka1VYdWpNVW4wT3FUVmRwTG50TGQ1Vm5sd205NjFKQW0wUUVRZkJ3UkRGVDA1Y08xVUhPZ2hQWWFmYmxuTVdqQ3ZtQlgrbWcyWnA2cz0=";
        TTvFunctionManager.getInstance(this).systemAuthorized(TSA_KEY);
        client = new TInputSourceClient();

        packageManager = new MyPackageManager(ctx);
        rtcTimeHelper = new RtcTimeHelper(ctx);
        hdmiCecHelper = new HDMICecHelper(ctx);
        mLedHelper = new LedHelper(ctx);

//        int mode = SystemProperties.getInt(defs.PERSIST_TVMODE, 1);
//        if (mode == 1) {
//            SystemProperties.set(defs.PERSIST_INSTALLAPK_ENABLE, "1");
//            SystemProperties.set(defs.PERSIST_DEBUG_INSTALLAPK, "1");
//            SystemProperties.set(defs.PERSIST_STANDBY_MODE, defs.SHUT_DOWN_STATE_OFF);
//        }

        try {
            Init();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        updateOtaData();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        client.release(); //onStop的时候调用
        AppUpdateManager.activityDestroy();
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return myIBinder;
    }

    void Init() throws RemoteException {
        SharedPreferences vPreferences = ctx.getSharedPreferences(dataPath, MODE);
        boolean value = vPreferences.getBoolean("factory_init", true);
        String deviceName = AHDeviceHelper.getDeviceName();
        Log.i(TAG, "getFactroyInit  " + value + " deviceName " + deviceName.isEmpty());
        if (!deviceName.isEmpty() && (!value)) {
            return;
        }
        setDeviceName();
        setLauncher();
        SharedPreferences.Editor editor = vPreferences.edit();
        editor.putBoolean("factory_init", false);
        editor.commit();
        int mode = SystemProperties.getInt(defs.PERSIST_TVMODE, 1);
        if (mode == 0) {
            setNormalData();
            return;
        }
        int flag = ThirdParty.mFactoryAdapter.getHotelFlag();
        if (flag == 1) {
            return;
        }
        SystemProperties.set(defs.PERSIST_TVMODE, "0");
    }

    public void setNormalData() {
        ThirdParty.mFactoryAdapter.closeSerialPort();
        SystemProperties.set("persist.sys.app.debug", "true");

        Log.i(TAG, "setSystemLogo   ");
        SystemProperties.set(defs.PERSIST_SYS_SYSLOGO, defs.LOGO_SYSTEM);
        ThirdParty.mFactoryAdapter.setHotelBootLogo(0);
    }

    public void setDeviceName() {
        String mac = myIBinder.getMac();
        String modelName = myIBinder.getModelName();
        String deviceName;
        if (modelName == null || modelName.trim().length() <= 0) {
            modelName = "Smart TV";
        }
        if (mac == null || mac.trim().length() <= 0) {
            mac = "0000";
        } else {
            mac = mac.replace(":", "").toUpperCase().substring(8, 12);
        }
        deviceName = "TCL " + modelName + "-" + mac;
        Log.i(TAG, "deviceName " + deviceName);
        boolean ret = AHDeviceHelper.setDeviceName(ctx, deviceName);
        Log.i(TAG, "ret " + ret);
    }

    private void initGpio() {
        try {
            String clientType = myIBinder.getClientType();
            Log.i(TAG, "init GpioHelper() clientType " + clientType);
            if (!clientType.contains("TCL-CN-T963-G90E")) {
                return;
            }
            mGpioHelper = new GpioHelper();
            mGpioHelper.initGPIO();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public AssetManager getAssets() {
        return super.getAssets();
    }

    private void initLedMode() {
        try {
            int value = myIBinder.getFastboot();
            String clientType = myIBinder.getClientType();
            if (!clientType.contains("TCL-CN-T963-G90E")) {
                return;
            }
            Log.i(TAG, "initLedMode() fastBoot " + value);
            mLedHelper.initLedMode(value);
            if (value == defs.FAST_SOUND_BOX || value == defs.FAST_BOOT_ON) {
                mGpioHelper.setGPIO(483, 1);
            } else {
                mGpioHelper.setGPIO(483, 0);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    class MyIBinder extends ICustomerApi.Stub {
        @Override
        public String getCurrentInputSource() {

            String str = ThirdParty.getSourceType();
            Log.i(TAG, "getCurrentInputSource  " + str);
            return str;
        }

        @Override
        public void setCurrentInputSource(String value) {
            if (value.equalsIgnoreCase(STROAGE) || value.equalsIgnoreCase(STROAGE1)) {
                client.request(); //创建实例的时候调用
                client.setInputSourceLazy(EnTCLInputSource.EN_TCL_STORAGE);
                Log.i(TAG, "setCurrentInputSource0  " + value);
            } else {
                int temp = handleSourceDataToSave(value);
                ThirdParty.setSourceTypeApi(temp);
            }
            Log.i(TAG, "setCurrentInputSource  " + value);
        }

        @Override
        public int getCurrentTVChannel() {
            int channel = ThirdParty.getCurrentChannelNumber();
            Log.i(TAG, "getCurrentTVChannel  " + channel);
            return channel;
        }

        @Override
        public void setCurrentTVChannel(int value) {
            List<ProgramInfo> atvchlList = ThirdParty.mTvChannelManager.getChannelList(EnTCLChanelListType.EN_CHANNEL_ANALOGUE);
            List<ProgramInfo> dtvchlList = ThirdParty.mTvChannelManager.getChannelList(EnTCLChanelListType.EN_CHANNEL_DIGINAL);

            int valueTemp = value;
            if (valueTemp > 9000) {
                valueTemp = valueTemp - 9000;
            }
            Log.i(TAG, "valueTemp," + valueTemp);
            String str = ThirdParty.getSourceTypeApi();
            if (str.equalsIgnoreCase(DEFS.DTV)) {
                if (dtvchlList == null || dtvchlList.size() <= 0 || valueTemp > dtvchlList.size()) {
                    Log.i(TAG, "dtv list is null");
                    return;
                }
                ThirdParty.selectProgramDTV(valueTemp);
            } else if (str.equalsIgnoreCase(DEFS.ATV)) {
                if (atvchlList == null || atvchlList.size() <= 0 || valueTemp > atvchlList.size()) {
                    Log.i(TAG, "ATV list is null");
                    return;
                }
                ThirdParty.selectProgram(value);
            }
            Log.i(TAG, "setCurrentTVChannel  " + value);
        }

        /**
         * 设置信源的画面比例及起始位置
         *
         * @param x 画面左上角的X坐标
         * @param y 画面左上角的y坐标
         * @param w 画面的宽度
         * @param h 画面的高度
         * @return 设置的结果
         * <-em->true<-em->    success
         * <-em->false<-em->    failed
         * 备注：x、y、w、h均设置为65535时，即表示将画面设置为全屏显示
         * @data 2021/1/29 11:08
         */
        @Override
        public boolean scaleWindow(int x, int y, int w, int h) {
            final VideoWindowRect videoWindowType = new VideoWindowRect();
            videoWindowType.x = x;
            videoWindowType.y = y;
            videoWindowType.width = w;
            videoWindowType.height = h;
            try {
                if (TTvPictureManager.getInstance(ctx) != null) {
                    Log.v(TAG,
                            "scale cyberUI window time="
                                    + System.currentTimeMillis() + ";threadid="
                                    + Thread.currentThread().getId());
                    TTvPictureManager.getInstance(ctx).scaleVideoWindow(
                            EnTCLWindow.EN_TCL_MAIN, videoWindowType);
                    return true;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return false;
        }

        @Override
        public void setPowerOnTVChannel(int value) throws RemoteException {
            int sourceIndex = ThirdParty.getHotelAttribute(FactoryManager.FACTORY_ATTR_HOTEL_SOURCE, 0);
            int channelNum = ThirdParty.getHotelAttribute(FactoryManager.FACTORY_ATTR_HOTEL_POWER_ATV_CH, 0);
            List<ProgramInfo> tvchlList = null;
            int totalsize;
            int i;
            Log.i(TAG, " sourceIndex " + sourceIndex);
            if (sourceIndex == DEFS.HOTEL_SOURCE_ATV) {
                tvchlList = ThirdParty.mTvChannelManager.getChannelList(EnTCLChanelListType.EN_CHANNEL_ANALOGUE);
            } else if (sourceIndex == DEFS.HOTEL_SOURCE_DTV) {
                tvchlList = ThirdParty.mTvChannelManager.getChannelList(EnTCLChanelListType.EN_CHANNEL_DIGINAL);
            }
            if (tvchlList != null) {
                totalsize = tvchlList.size();
                Log.i(TAG, "size : " + totalsize);
                if (totalsize > 0) {
                    Log.i(TAG, "tvchlList is not null and its size > 0");
                    for (i = 0; i < totalsize; i++) {
                        if (tvchlList.get(i).number == value) {
                            break;
                        }
                    }
                    if (i == totalsize)    //do not find number
                    {
                        channelNum = tvchlList.get(0).number;

                    } else {
                        channelNum = value;
                    }
                    ThirdParty.setHotelAttribute(FactoryManager.FACTORY_ATTR_HOTEL_POWER_ATV_CH, channelNum);
                }
            }
            Log.i(TAG, "mtvChannelManager equal NULL? : " + (ThirdParty.mTvChannelManager == null) + "");
            Log.i(TAG, "tvchlList equal NULL? : " + (tvchlList == null) + "");
            Log.i(TAG, "setPowerOnTVChannel " + channelNum);
        }

        @Override
        public void setPowerOnInputSource(String value) throws RemoteException {
            int temp = handleSourceDataToSave(value);
            Log.i(TAG, "setPowerOnInputSource  " + value + " temp " + temp);
            ThirdParty.setHotelAttribute(FactoryManager.FACTORY_ATTR_HOTEL_SOURCE, temp);
        }

        @Override
        public void setPowerOnVolume(int value) throws RemoteException {
            Log.i(TAG, "setPowerOnVolume  " + value);
            if (value >= 0 && value <= 100) {
                TV.writeV(TVDefine.Hotel_PresetVolume, value);
            }
        }

        @Override
        public void setPowerOnPicture(String value) {
            Log.i(TAG, "setPowerOnPicture  " + value);
            if (getHotelMode() == 0) {
                sendBroadcast(new Intent(defs.MSG_CHANNEL_ERR));
                return;
            }
            ThirdParty.setLogoApi(value);
        }


        @Override
        public void setFastboot(int value) throws RemoteException {
            Log.i(TAG, "setFastboot  " + value);
            if (value == 1) {
                value = defs.FAST_BOOT_ON;
            }
            if (value == defs.FAST_BOOT_OFF || value == defs.FAST_BOOT_ON) {
                SystemProperties.set(defs.PERSIST_FASTPOWER, String.valueOf(value));
            } else {
                if (value == defs.FAST_SOUND_BOX) {
                    //音箱模式
                    SystemProperties.set(defs.PERSIST_FASTPOWER, String.valueOf(value));
                    //音箱模式自动开启远场语音
                    TSoundManager tsoundmanager = TSoundManager.getInstance(ctx);
                    EnTCLAudioDeviceType v = EnTCLAudioDeviceType.EN_TCL_DEVICE_TYPE_FFVR_ENGINE;
                    tsoundmanager.setDeviceOutputEnable(v, true, 2);

                }
                Log.i(TAG, "Illegal parameter");
            }
            initLedMode();
        }

        @Override
        public void setKeylock(boolean value) throws RemoteException {
            Log.i(TAG, "setKeylock  " + value);
            TV.writeS(TVDefine.KeyLock, value);
        }

        @Override
        public int getBrightness() {
            int value = TV.readV(TVDefine.Brightness);
            Log.i(TAG, "getBrightness  " + value);
            return value;
        }

        @Override
        public void setBrightness(int value) {
            Log.i(TAG, "setBrightness  " + value);
            TV.writeV(TVDefine.Brightness, value);
        }

        @Override
        public int getBacklight() {
            int value = TV.readV(TVDefine.BackLight);
            Log.i(TAG, "getBacklight  " + value);
            return value;
        }

        @Override
        public void setBacklight(int value) {
            Log.i(TAG, "setBacklight  " + value);
            TV.writeV(TVDefine.BackLight, value);
        }


        @Override
        public int getContrast() {
            int value = TV.readV(TVDefine.Contrast);
            Log.i(TAG, "getContrast  " + value);
            return value;
        }

        @Override
        public void setContrast(int value) {
            Log.i(TAG, "setContrast  " + value);
            TV.writeV(TVDefine.Contrast, value);
        }

        @Override
        public void powerOffSystem() {
            Log.i(TAG, "powerOffSystem  ");
            TTvFunctionManager tvFuncMgr = TTvFunctionManager.getInstance(ctx);
            if (tvFuncMgr != null) {
                tvFuncMgr.powerOff(EnTCLPowerOffType.EN_POWEROFF_TYPE_NORMAL);
            }
        }

        @Override
        public void rebootSystem() throws RemoteException {
            Log.i(TAG, "rebootSystem  ");
            Intent intent2 = new Intent(Intent.ACTION_REBOOT);
            intent2.putExtra("nowait", 1);
            intent2.putExtra("interval", 1);
            intent2.putExtra("window", 0);
            ctx.sendBroadcast(intent2);
        }


        @Override
        public void setCec(boolean value) throws RemoteException {
            Log.i(TAG, "setCec  " + value);
            hdmiCecHelper.setTLinkEnable(value);
        }

        @Override
        public void setPowerOnMode(String value) throws RemoteException {
            if ((value.equalsIgnoreCase("direct") || value.equalsIgnoreCase("secondary") || value.equalsIgnoreCase("memory"))) {
                int intValue = 0;
                if (value.equalsIgnoreCase("direct")) {
                    intValue = 1;
                } else if (value.equalsIgnoreCase("secondary")) {
                    intValue = 0;
                } else if (value.equalsIgnoreCase("memory")) {
                    intValue = 2;
                }
                TV.writeV(TVDefine.PowerMode, intValue);
                Log.i(TAG, "setPowerOnMode    " + value);
            }
        }

        @Override
        public String getPowerOnMode() {
            String mode = "";
            int value = TV.readV(TVDefine.PowerMode);
            if (value == 1) {
                mode = "direct";
            } else if (value == 0) {
                mode = "secondary";
            } else if (value == 2) {
                mode = "memory";
            }
            Log.i(TAG, "poweron mode is   " + mode);
            return mode;
        }

        @Override
        public int getPowerOnTVChannel() {
            int currentChannelNum = ThirdParty.getHotelAttribute(FactoryManager.FACTORY_ATTR_HOTEL_POWER_ATV_CH, 0);
            Log.i(TAG, "getPowerOnTVChannel  " + currentChannelNum);
            return currentChannelNum;
        }

        @Override
        public String getPowerOnInputSource() {
            int currentSourceIndex = ThirdParty.getHotelAttribute(FactoryManager.FACTORY_ATTR_HOTEL_SOURCE, 0);
            String str = handleSourceData(currentSourceIndex);
            Log.i(TAG, "getPowerOnInputSource  " + str);
            return str;
        }

        @Override
        public int getPowerOnVolume() {
            int value = TV.readV(TVDefine.Hotel_PresetVolume);
            Log.i(TAG, "getPowerOnVolume  " + value);
            return value;
        }

        @Override
        public int getFastboot() throws RemoteException {
            int flag = SystemProperties.getInt(defs.PERSIST_FASTPOWER, 0);
            Log.i(TAG, "getFastboot  " + flag);
            return flag;
        }

        @Override
        public boolean getKeylock() {
            boolean value = TV.readS(TVDefine.KeyLock);
            Log.i(TAG, "getKeylock  " + value);
            return value;
        }

        @Override
        public boolean getCec() {
            boolean isTLinkEnable = hdmiCecHelper.getTLinkEnable();
            Log.i(TAG, "getCec  " + isTLinkEnable);
            return isTLinkEnable;
        }

        @Override
        public void setPowerOnBootanimation(String value) {
            Log.i(TAG, "setPowerOnBootanimation  " + value);
            if (getHotelMode() == 0) {
                sendBroadcast(new Intent(defs.MSG_CHANNEL_ERR));
                return;
            }
            ThirdParty.setUserBootAnimation(value);
        }

        @Override
        public void setPowerOnVideo(String value) {
            Log.i(TAG, "setPowerOnVideo  " + value);
            if (getHotelMode() == 0) {
                sendBroadcast(new Intent(defs.MSG_CHANNEL_ERR));
                return;
            }
            ThirdParty.setVideoApi(value);
        }

        @Override
        public void channelBackup(String value) {
            Log.i(TAG, "channelBackup   path  " + value);
            if (null == value || ("".equals(value))) {
                ThirdParty.mContext.sendBroadcast(new Intent(defs.MSG_NO_USB_MOUNT));
                return;
            }
            TvManager.getInstance(ctx).getProperty().set("memory.factory.hotel.userpath", value);
            ThirdParty.NVM2USB_ChannelDate(1);
        }

        @Override
        public void channelRestore(String value) {
            Log.i(TAG, "channelBackup   path  " + value);
            if (null == value || ("".equals(value))) {
                Intent intent = new Intent(defs.MSG_NO_USB_MOUNT);
                ThirdParty.mContext.sendBroadcast(intent);
                return;
            }
            TvManager.getInstance(ctx).getProperty().set("memory.factory.hotel.userpath", value);
            ThirdParty.USB2NVM_ChannelDate(1);
        }

        //
        @Override
        public int getPowerPM() {
            int pictureIndex = ThirdParty.getHotelAttribute(FactoryManager.FACTORY_ATTR_HOTEL_PICTURE_MODE, 0);
            Log.i(TAG, "getPowerPM  " + pictureIndex);
            return pictureIndex;
        }

        @Override
        public void setPowerPM(int value) throws RemoteException {
            if (getHotelMode() == 0) {
                return;
            }
            ThirdParty.setHotelAttribute(FactoryManager.FACTORY_ATTR_HOTEL_PICTURE_MODE, value);
            Log.i(TAG, "setPowerPM  " + value);
        }

        //0：待机亮   1：待机灭   2：待机呼吸灯
        @Override
        public int getLed() {
            int value = TV.readV(TVDefine.StandbyLEDIndicatorMode);
            Log.i(TAG, "getLed  " + value);
            return value;
        }

        @Override
        public void setLed(int value) throws RemoteException {
            String clientType = myIBinder.getClientType();
            //如果机型为G90E。LED灯设置为待机灭灯
            if (clientType.contains("TCL-CN-T963-G90E")) {
                value = 1;
            }
            if (value > 2 || value < 0) {
                return;
            }
            SystemProperties.set(defs.PERSIST_LED, "" + value);
            TV.writeV(TVDefine.StandbyLEDIndicatorMode, value);
            Log.i(TAG, "setLed  " + value);
        }

        @Override
        public boolean getUart() {
            boolean value = ThirdParty.mFactoryAdapter.getUartStatus();
            Log.i(TAG, "getUart  " + value);
            return value;
        }

        @Override
        public void setUart(boolean value) throws RemoteException {
            if (value) {
                ThirdParty.mFactoryAdapter.openSerialPort();
            } else {
                ThirdParty.mFactoryAdapter.closeSerialPort();
            }
            Log.i(TAG, "setUart  " + value);
        }

        @Override
        public int getMaxVolume() {
            int value = TV.readV(TVDefine.Hotel_MaxVolume);
            Log.i(TAG, "getMaxValue  " + value);
            return value;
        }

        @Override
        public void setMaxVolume(int value) throws RemoteException {
            if (value >= 0 && value <= 100) {
                TV.writeV(TVDefine.Hotel_MaxVolume, value);
            }
            Log.i(TAG, "setMaxValue  " + value);
        }

        @Override
        public String getMac() {
            String str = ThirdParty.getMACAddressString();
            Log.i(TAG, "getMac  " + str);
            if (str == null) {
                return ThirdParty.getEthMacAddress(true);
            }
            return str;
        }

        @Override
        public void setMac(int arg1, int arg2, int arg3, int arg4, int arg5, int arg6) {
        }

        @Override
        public boolean getAutoRedirectionStatus() {
            return true;
        }

        @Override
        public void setAutoRedirectionStatus(boolean value) {
        }

        @Override
        public String getAutoRedirectionApp() {
            return "";
        }

        @Override
        public void setAutoRedirectionApp(String value) {
        }

        @Override
        public int getAutoRedirectionTime() {
            return 0;
        }

        @Override
        public void setAutoRedirectionTime(int value) {
        }

        @Override
        public void setTrace(boolean value) {
            if (value) {
                SystemProperties.set(defs.PERSIST_USB_CONFIG, "adb");
                SystemProperties.set(defs.PERSIST_USB_CONFIG2, "adb");
            } else {
                SystemProperties.set(defs.PERSIST_USB_CONFIG, "none");
                SystemProperties.set(defs.PERSIST_USB_CONFIG2, "none");
            }
            Log.i(TAG, "setTrace  " + value);
        }

        @Override
        public boolean getTrace() {
            return "running".equals(SystemProperties.get("init.svc.adbd",""));
        }

        @Override
        public void setMemoryClean(int value) {
            SystemProperties.set(defs.PERSIST_SYS_CACHECEAR, String.valueOf(value));
            Log.i(TAG, "setMemoryClean  " + value);
        }

        @Override
        public int getMemoryClean() {
            int flag = SystemProperties.getInt(defs.PERSIST_SYS_CACHECEAR, 0);
            Log.i(TAG, "getMemoryClean  " + flag);
            return flag;
        }


        @Override
        public void setCamera(boolean value) {
        }

        @Override
        public boolean getCamera() {
            return false;
        }

        @Override
        public void setCameraTime(int value) {
        }

        @Override
        public int getCameraTime() {
            return 0;
        }

        @Override
        public void setCameraPosit(int value) {
        }

        @Override
        public int getCameraPosit() {
            return 0;
        }

        @Override
        public void setCameraSize(int value) {
        }

        @Override
        public int getCameraSize() {
            return 0;
        }

        @Override
        public int getHotelMode() {
//            int flag = SystemProperties.getInt(defs.PERSIST_TVMODE, 0);
//            int flag_hotel = SystemProperties.getInt(DEFS.HOTEL_PROPERTY_HOTEL_HOTKEY, 0);
//            Log.i(TAG, "getHotelMode  " + (flag & flag_hotel));
//            return flag & flag_hotel;
            int flag = ThirdParty.mFactoryAdapter.getHotelFlag();
            Log.d(TAG, "getHotelMode: " + flag);
            return flag;
        }

        @Override
        public void setHotelMode(int value) throws RemoteException {
            if (value == 1) {
                ThirdParty.mFactoryAdapter.setHotelFlag(1);
            } else if (value == 2) {
                ThirdParty.mFactoryAdapter.setHotelFlag(1);
                ThirdParty.mFactoryAdapter.setHotelAttribute(FactoryManager.FACTORY_ATTR_HOTEL_AUTO_SET, 1);
            } else {
                ThirdParty.mFactoryAdapter.setHotelFlag(0);
                ThirdParty.mFactoryAdapter.setHotelAttribute(FactoryManager.FACTORY_ATTR_HOTEL_AUTO_SET, 0);
            }
            /*
            SystemProperties.set(defs.PERSIST_TVMODE, String.valueOf(value));
            SystemProperties.set(DEFS.HOTEL_PROPERTY_HOTEL_HOTKEY, String.valueOf(value));
            if (value == 1) {
                SystemProperties.set(defs.PERSIST_INSTALLAPK_ENABLE, "1");
                SystemProperties.set(defs.PERSIST_DEBUG_INSTALLAPK, "1");

                //取消十五秒待机
                Log.i(TAG, "set persist.sys.standbymode 0");
                SystemProperties.set(defs.PERSIST_STANDBY_MODE, defs.SHUT_DOWN_STATE_OFF);
                //关闭串口
                ThirdParty.mFactoryAdapter.closeSerialPort();
                //打开频道锁
                ThirdParty.mFactoryAdapter.setHotelCNClock(1);

                ThirdParty.mFactoryAdapter.setHotelFlag(value);
                ThirdParty.mFactoryAdapter.setHotelAttribute(FactoryManager.FACTORY_ATTR_HOTEL_AUTO_SET, value);
                SystemProperties.set(defs.PERSIST_FACTORY_HOTEL_FLAG, "1");
                if (getPowerOnLogoStatus() == 1) {
                    setPowerOnPicture(defs.USER_PATCH_POWERON_SHOW);
                }
                SharedPreferences vPreferences = ctx.getSharedPreferences(dataPath, MODE);
                boolean initFlag = vPreferences.getBoolean("first_init", true);
                Log.i(TAG, "first_init" + initFlag);
                if (initFlag) {
                    SharedPreferences.Editor editor = vPreferences.edit();
                    editor.putBoolean("first_init", false).commit();
                    recovery();
                }
            } else if (value == 2) {
                ThirdParty.mFactoryAdapter.setHotelFlag(1);
                ThirdParty.mFactoryAdapter.setHotelAttribute(FactoryManager.FACTORY_ATTR_HOTEL_AUTO_SET, 1);
                SystemProperties.set(defs.PERSIST_FACTORY_HOTEL_FLAG, "1");
            } else {
                SystemProperties.set(defs.PERSIST_INSTALLAPK_ENABLE, "1");
                SystemProperties.set(defs.PERSIST_DEBUG_INSTALLAPK, "1");
                ThirdParty.mFactoryAdapter.setHotelFlag(0);
                ThirdParty.mFactoryAdapter.setHotelAttribute(FactoryManager.FACTORY_ATTR_HOTEL_AUTO_SET, 0);
                SystemProperties.set(defs.PERSIST_FACTORY_HOTEL_FLAG, "0");
                int boot_logo_mode = ThirdParty.mFactoryAdapter.getHotelBootLogo();
                if (boot_logo_mode != DEFS.HOTEL_DEFAULT_LOGO) {
                    ThirdParty.mFactoryAdapter.setHotelBootLogo(DEFS.HOTEL_DEFAULT_LOGO);
                }
                //关闭串口
                ThirdParty.mFactoryAdapter.closeSerialPort();
                //打开十五秒待机
                Log.i(TAG, "set persist.sys.standbymode 1");
                SystemProperties.set(defs.PERSIST_STANDBY_MODE, defs.SHUT_DOWN_STATE_ON);
                //取消频道锁
                ThirdParty.mFactoryAdapter.setHotelCNClock(0);
            }
            sendSystemModeChangerBroadcast();
            Log.i(TAG, "setHotelMode  " + value);
            */
        }

        void recovery() {
            try {
                setPowerOnInputSource("AV");
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            try {
                setPowerOnTVChannel(1);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            try {
                setMaxVolume(100);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            try {
                setPowerOnVolume(15);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            try {
                setPowerPM(0);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            try {
                setKeylock(false);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            try {
                setSystemLogo();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            try {
                setSystemBootanimation();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            try {
                setPowerOnMode("direct");
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            try {
                setFastboot(0);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            try {
                setLed(1);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            try {
                SystemProperties.set("persist.sys.app.debug", "true");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void setLauncher(String value) throws RemoteException {
            PackageManager pm = ctx.getPackageManager();
            Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
            mainIntent.addCategory(Intent.CATEGORY_HOME);
            List<ResolveInfo> mResolveInfo = pm.queryIntentActivities(mainIntent, PackageManager.GET_DISABLED_COMPONENTS);
            boolean flag = false;
            if ("com.tcl.tv".equals(value)) {
                String temp = getLauncher();
                SystemProperties.set(defs.PERSIST_LAUNCHER_NAME, value);
                Log.i(TAG, "setLauncher  " + value);
                if (!value.equals(temp)) {
                    systemSafe();
                }
                return;
            }
            for (ResolveInfo resolveInfo : mResolveInfo) {
                if (value.equals(resolveInfo.activityInfo.packageName)) {
                    flag = true;
                    break;
                }
            }
            if (flag) {
                String temp = getLauncher();
                SystemProperties.set(defs.PERSIST_LAUNCHER_NAME, value);
                if (!value.equals(temp)) {
                    systemSafe();
                }
                String cmpName = doStartApplicationWithPackageName(value);
                boolean result = Settings.System.putString(ctx.getContentResolver(), defs.BOOT_APP_COMPONENTNAME, cmpName);
                Log.i(TAG, "setLauncher  " + value + " cmpName " + cmpName + " result " + result);
            }
        }

        private String doStartApplicationWithPackageName(String packageName) {
            String className = null;
            Intent launch = new Intent();
            launch.setPackage(packageName);
            Log.d(TAG, "startPackageActivity tarPackage " + packageName);
            PackageManager pm = ctx.getPackageManager();
            List<ResolveInfo> resolveInfos = pm.queryIntentActivities(launch, STOCK_PM_FLAGS | MATCH_DIRECT_BOOT_UNAWARE);
            Collections.sort(resolveInfos, new ResolveInfo.DisplayNameComparator(pm));
            if (resolveInfos.size() > 0) {
                ActivityInfo activity = resolveInfos.get(0).activityInfo;
                Log.d(TAG, "Start app, PackageName:" + activity.applicationInfo.packageName + "    ActivityName:" + activity.name);
                className = activity.name;
            } else {
                Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
                mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
                List<ResolveInfo> mResolveInfo = pm.queryIntentActivities(mainIntent, 0);
                for (ResolveInfo resolveInfo : mResolveInfo) {
                    String packName = resolveInfo.activityInfo.packageName;
                    if (packageName.equals(packName)) {
                        className = resolveInfo.activityInfo.name;
                    }
                }
                if (className == null) {
                    switch (packageName) {
                        case "com.tcl.cyberui":
                            className = "com.tcl.cyberui.MainActivity";
                            break;
                        case "com.tcl.workmode":
                            className = "com.tcl.workmode.portal.MainActivity";
                            break;
                        default:
                            packageName = "com.tcl.tv";
                            className = "com.tcl.tv.TVActivity";
                            break;
                    }
                }
            }
            return packageName + "/" + className;
        }

        private void systemSafe() {
            String packageName = "com.android.systemservice";
            String serviceName = "com.android.systemservice.server.TclIntentService";
            Intent intent = new Intent();
            intent.setClassName(packageName, serviceName);
            intent.setAction("connect_server");
            intent.putExtra("index_order", 4);
            ctx.startService(intent);
            Log.i(TAG, "system safe");
        }

        @Override
        public String getLauncher() throws RemoteException {
            return SystemProperties.get(defs.PERSIST_LAUNCHER_NAME, "");
        }

        @Override
        public void setRoom(String value) {
            SystemProperties.set(defs.PERSIST_HOTEL_ROOM, value);
            Log.i(TAG, "setRoom  " + value);
        }

        @Override
        public String getRoom() {
            String value = SystemProperties.get(defs.PERSIST_HOTEL_ROOM, "");
            Log.i(TAG, "getRoom  " + value);
            return value;
        }

        @Override
        public void setHotelId(String value) {
            SystemProperties.set(defs.PERSIST_HOTEL_ID, value);
            Log.i(TAG, "setHotelId  " + value);
        }

        @Override
        public String getHotelId() {
            String value = SystemProperties.get(defs.PERSIST_HOTEL_ID, "");
            Log.i(TAG, "getHotelId  " + value);
            return value;
        }

        @Override
        public void setTVSource(String value) {
        }

        @Override
        public String getTVSource() {
            return "";
        }

        @Override
        public void setServiceIp(String value) {
        }

        @Override
        public String getServiceIp() {
            return "";
        }

        @Override
        public void setPort(int value) {
        }

        @Override
        public int getPort() {
            return 0;
        }

        @Override
        public void setLogin(String value) {
        }

        @Override
        public String getLogin() {
            return "";
        }

        @Override
        public void setRegister() {
        }

        @Override
        public void setURL(String value) {
        }

        @Override
        public String getURL() {
            return "";
        }

        @Override
        public void setUrlDuration(int value) {
        }

        @Override
        public int getUrlDuration() {
            return 0;
        }

        @Override
        public void setDefaultDisplay(boolean value) {
        }

        @Override
        public boolean getDefaultDisplay() {
            return false;
        }

        @Override
        public String getSoftwareVersion() {
            String ver = ThirdParty.getSoftwareVersion();
            Log.i(TAG, "getSoftwareVersion   " + ver);
            return ver;
        }

        @Override
        public void setFactroyInit(boolean value) {
        }

        @Override
        public boolean getFactroyInit() {
            return true;
        }

        @Override
        public void setCallBack(ICallBack value) {
        }

        @Override
        public void setDefaultLogoBootanimation() {
            ThirdParty.mFactoryAdapter.setHotelBootLogo(0);
            ThirdParty.setHotelBootAnimation(0);
            ThirdParty.setHotelBootVideo(0);
            SystemProperties.set(defs.PERSIST_SYS_SYSLOGO, defs.LOGO_SYSTEM);
            SystemProperties.set(defs.PERSIST_SYS_SYSBOOTANIMATION, defs.BOOTANIMATION_SYSTEM);
        }

        @Override
        public boolean getScreenStatus() {
            return SystemProperties.getBoolean(defs.PERSIST_SCREEN_STATUS, true);
        }

        @Override
        public void simulateKeyboard(int keyCode) throws RemoteException {
            sendKeyThread(keyCode);
        }

        @Override
        public List<String> getChannelListStr() {
            List<ProgramInfo> channelInfoList;
            List<String> list = new ArrayList<String>();
            list.clear();
            channelInfoList = channelManager.getChannelList(EnTCLChanelListType.EN_CHANNEL_ALL);
            for (ProgramInfo tempInfo : channelInfoList) {
                String str;
                if (tempInfo.serviceType == EnTCLMemberServiceType.EN_TCL_ATV) {
                    str = "ATV_" + tempInfo.number;
                } else {
                    str = "DTV_" + tempInfo.number;
                }
                list.add(str);
            }
            Log.i(TAG, "CH  " + list.size());
            return list;
        }

        @Override
        public boolean takeScreenshot(String path) {
            Log.i(TAG, "start ----takeScreenshot---- path " + path);
            //截图的数据流
            byte[] result;
            try {
                Class<?> mAppManager = Class.forName("com.tcl.app.AppManager");
                Class<?> mScreenshot = Class.forName("com.tcl.app.screenshot.Screenshot");
                Method getInstance = mAppManager.getMethod("getInstance", Context.class);
                Method getScreenshot = mAppManager.getMethod("getScreenshot");
                Object objAppManager = getInstance.invoke(mAppManager, ctx);
                Object objScreenshot = getScreenshot.invoke(objAppManager);
                Method snapshot = mScreenshot.getMethod("snapshot", int.class, Rect.class, int.class, int.class, int.class);
                int width = 1920;
                int height = 1080;
                result = (byte[]) snapshot.invoke(objScreenshot, 255, new Rect(0, 0, width, height), 3, width, height);
                try {
                    File file = new File(path);
                    FileOutputStream fos = new FileOutputStream(file);
                    fos.write(result, 0, result.length);
                    fos.flush();
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                    return false;
                }

            } catch (Exception e) {
                Log.e(TAG, "catch exception ----> " + e);
                return false;
            }
            Log.i(TAG, "complete ----takeScreenshot----");
            return true;
        }

        @Override
        public boolean getAudioMuteStatus() {
            boolean value = ThirdParty.getAudioMuteStatus();
            Log.i(TAG, "getAudioMuteStatus  " + value);
            return value;
        }

        @Override
        public void setAudioMuteStatus(boolean status) {
            Log.i(TAG, "setAudioMuteStatus  " + status);
            ThirdParty.setAudioMuteStatus(status);
        }

        @Override
        public int getAudioVolumeValue() {
            int value = ThirdParty.getAudioVolumeValue();
            Log.i(TAG, "getAudioVolumeValue  " + value);
            return value;
        }

        @Override
        public void setAudioVolumeValue(int value) {
            Log.i(TAG, "setAudioVolumeValue  " + value);
            ThirdParty.setAudioVolumeValue(value);
        }

        @Override
        public void setPictureFormatValue(int mode) {
            Log.i(TAG, "setPictureFormatValue  " + mode);
            ThirdParty.setPictureFormatValue(mode);
        }

        @Override
        public int getPictureFormatValue() {
            int mode = ThirdParty.getPictureFormatValue();
            Log.i(TAG, "getPictureFormatValue  " + mode);
            return mode;
        }

        @Override
        public boolean channelData2System(String path) {
            Log.i(TAG, "channelData2System  " + path);
            ThirdParty.setRootSeek("cp -f /" + path + "/AtvData.db /userdata/AtvData.db");
            ThirdParty.setRootSeek("cp -f /" + path + "/DtvData.db /userdata/DtvData.db");

            ThirdParty.setRootSeek("chmod 666 " + "/userdata/AtvData.db");
            ThirdParty.setRootSeek("chmod 666 " + "/userdata/DtvData.db");
            ThirdParty.setRootSeek("sync");
            return true;
        }

        @Override
        public boolean setPowerOnDisplay(int index, String path) {
            Log.i(TAG, "setPowerOnDisplay start --->");
            Log.i(TAG, "id   " + index + "   path   " + path);
            ThirdParty.setRootSeek("tclsu");
            ThirdParty.setRootSeek("mount -o remount /system");

            if (index == defs.SET_TEMPLET) {

                ThirdParty.setRootSeek("chmod 777  " + defs.NO_LOGO_PATH + defs.ANIMTTEMPLET);
                ThirdParty.setRootSeek("chmod 777  " + defs.MEDIA_PATH + defs.ANIMTTEMPLET);
                ThirdParty.setRootSeek("busybox cp  -rf " + path + "  " + defs.NO_LOGO_PATH + defs.ANIMTTEMPLET);
                ThirdParty.setRootSeek("busybox cp  -rf " + path + "  " + defs.MEDIA_PATH + defs.ANIMTTEMPLET);
                ThirdParty.setRootSeek("chmod 777  " + defs.NO_LOGO_PATH + defs.ANIMTTEMPLET);
                ThirdParty.setRootSeek("chmod 777  " + defs.MEDIA_PATH + defs.ANIMTTEMPLET);
            } else if (index == defs.SET_ADBOOT) {
                ThirdParty.setRootSeek("chmod 777  " + defs.NO_LOGO_PATH + defs.ANIMTTEMPLET);
                ThirdParty.setRootSeek("chmod 777  " + defs.MEDIA_PATH + defs.ANIMTTEMPLET);
                ThirdParty.setRootSeek("busybox cp  -rf " + path + "  " + defs.MEDIA_PATH + defs.ADBOOTANIMATION);
                ThirdParty.setRootSeek("busybox cp  -rf " + path + "  " + defs.NO_LOGO_PATH + defs.ADBOOTANIMATION);
                ThirdParty.setRootSeek("chmod 777  " + defs.MEDIA_PATH + defs.ADBOOTANIMATION);
                ThirdParty.setRootSeek("chmod 777  " + defs.NO_LOGO_PATH + defs.ADBOOTANIMATION);
            }

            ThirdParty.setRootSeek("sync");
            Log.i(TAG, "setPowerOnDisplay end <---");
            return false;
        }

        @Override
        public int getChannelSize(String type) {
            int size = 0;
            List<ProgramInfo> channelInfoList;
            channelInfoList = channelManager.getChannelList(EnTCLChanelListType.EN_CHANNEL_ALL);
            for (ProgramInfo tempInfo : channelInfoList) {
                if (type != null && type.equalsIgnoreCase("ATV") && tempInfo.serviceType == EnTCLMemberServiceType.EN_TCL_ATV) {
                    size++;
                } else if (type != null && type.equalsIgnoreCase("DTV") && tempInfo.serviceType == EnTCLMemberServiceType.EN_TCL_DTV) {
                    size++;
                }
            }
            return size;
        }

        @Override
        public String getDeviceID() {
            return ThirdParty.mFactoryAdapter.getDeviceID();
        }

        @Override
        public boolean setPowerOnAdbootanimation(String path) throws RemoteException {
            return false;
        }

        @Override
        public boolean setPowerOnAnimtemplet(String path) throws RemoteException {
            return false;
        }

        @Override
        public boolean setHotelData(String value) {
            final String strValue = value;
            Log.i(TAG, "setHotelData   " + value);
            if (getHotelMode() == 0) {
                return false;
            }
            new Thread(() -> {
                String projectName = ThirdParty.getProjectName();
                String modeStr = projectName.substring(2);
                if (modeStr.equals("A360J")) {

                } else if (modeStr.contains("A36")) {
                    modeStr = "A36X";
                } else if (modeStr.contains("A26")) {
                    modeStr = "A26X";
                }

                HotelDataUnit unit = new HotelDataUnit();
                try {
                    MyJSON json = new MyJSON(ctx);
                    String temp = json.DecodeJSON(strValue);
                    JSONObject object = new JSONObject(temp);
                    try {
                        if (object.get("ALL") != null) {
                            modeStr = "ALL";
                        }
                    } catch (Exception e) {
                        Log.i(TAG, "json is no all data  !");
                    }


                    temp = object.get(modeStr).toString();

                    Log.i(TAG, "setHotelData   " + temp);
                    JSONObject object1 = new JSONObject(temp);
                    unit.source = object1.getString(defs.JSON_SOURCE);
                    unit.channel = object1.getInt(defs.JSON_CHANNEL);
                    unit.volume = object1.getInt(defs.JSON_VOLUME);
                    unit.pictureMode = object1.getInt(defs.JSON_PICTRUE_MODE);
                    unit.keypadLock = object1.getInt(defs.JSON_KEYPAD_LOCK);
                    unit.maxVolume = object1.getInt(defs.JSON_MAX_VOLUME);
                    unit.advertLogo = object1.getInt(defs.JSON_LOGO);
                    unit.advertBootanimation = object1.getInt(defs.JSON_BOOTANIMATION);
                    unit.remoteDark = object1.getInt(defs.JSON_REMOTE_DARK);
                    unit.acMode = object1.getString(defs.JSON_AC_MODE);
                    unit.led = object1.getInt(defs.JSON_LED);
                    unit.uart = object1.getInt(defs.JSON_UART);
                    unit.cec = object1.getInt(defs.JSON_CEC);
                    unit.ip = object1.getString(defs.JSON_IP);
                    unit.launcher = object1.getString(defs.JSON_LAUNCHER);
                    Thread.sleep(200);
                    setPowerOnInputSource(unit.source);
                    Thread.sleep(200);
                    setPowerOnTVChannel(unit.channel);
                    Thread.sleep(200);
                    setPowerOnVolume(unit.volume);
                    Thread.sleep(200);
                    setPowerPM(unit.pictureMode);
                    Thread.sleep(200);
                    setKeylock(unit.keypadLock == 1);
                    Thread.sleep(200);
                    setMaxVolume(unit.maxVolume);
                    Thread.sleep(200);
                    //设置adb
                    setFastboot(unit.remoteDark == 0 ? 0 : 2);
                    Thread.sleep(200);
                    setPowerOnMode(unit.acMode);
                    Thread.sleep(200);
                    setLed(unit.led);
                    Thread.sleep(200);
                    setUart(unit.uart == 1);
                    Thread.sleep(200);
                    setCec(unit.cec == 1);
                    Thread.sleep(200);
                    sendBroadcast(new Intent(defs.MSG_USB_TO_NVM_OK));
                } catch (Exception e) {
                    Log.i(TAG, "Exception   " + e.getMessage());
                    e.printStackTrace();
                    sendBroadcast(new Intent(defs.MSG_USB_TO_NVM_NG));
                } finally {
                    Log.i(TAG, "finally   ");
                }
            }).start();

            return true;
        }

        @Override
        public String getHotelData() throws RemoteException {
            Log.i(TAG, "getHotelData   ");

            HotelDataUnit unit = new HotelDataUnit();
            String projectName = ThirdParty.getProjectName();

            String modeStr = projectName.substring(2);
            if (modeStr.equals("A360J")) {

            } else if (modeStr.contains("A36")) {
                modeStr = "A36X";
            } else if (modeStr.contains("A26")) {
                modeStr = "A26X";
            }
            unit.model = modeStr;//projectName.substring(2,projectName.length());
            unit.source = getPowerOnInputSource();
            unit.channel = getPowerOnTVChannel();
            unit.volume = getPowerOnVolume();
            unit.pictureMode = getPowerPM();//*******
            unit.keypadLock = getKeylock() ? 1 : 0;
            unit.maxVolume = getMaxVolume();
            unit.advertLogo = getPowerOnLogoStatus();//*************
            unit.advertBootanimation = getPowerOnBootanimation();//*********
            unit.acMode = getPowerOnMode();//****
            unit.remoteDark = getFastboot() == 2 ? 1 : 0;
            unit.led = getLed();
            unit.uart = getUart() ? 1 : 0;
            unit.cec = getCec() ? 1 : 0;
            unit.ip = getHostIP();
            unit.launcher = getLauncher();
            MyJSON json = new MyJSON(ctx);
            String str = json.EncodeJSON(json.createJSONObject(unit));
            Log.i(TAG, "getHotelData   " + str);
            return str;
        }

        @Override
        public boolean setSystemLogo() throws RemoteException {
            Log.i(TAG, "setSystemLogo");
            SystemProperties.set(defs.PERSIST_SYS_SYSLOGO, defs.LOGO_SYSTEM);
            ThirdParty.setHotelBootLogo(DEFS.HOTEL_DEFAULT_LOGO);
            return true;
        }

        @Override
        public boolean setSystemBootanimation() throws RemoteException {
            Log.i(TAG, "setSystemBootanimation   ");
            SystemProperties.set(defs.PERSIST_SYS_SYSBOOTANIMATION, defs.BOOTANIMATION_SYSTEM);
            ThirdParty.setHotelBootAnimation(0);
            ThirdParty.setHotelBootVideo(0);
            return true;
        }

        @Override
        public int getPowerOnLogoStatus() {
            return ThirdParty.mFactoryAdapter.getHotelBootLogo();
        }

        @Override
        public int getPowerOnBootanimation() {
            return ThirdParty.mFactoryAdapter.getHotelBootAnimation();
        }

        @Override
        public String getUSBMountPath() {
            String str = TclApplication.UdiskPATH;
            Log.i(TAG, "getUSBMountPath   " + str);
            if (str == null) {
                str = "";
            }
            return str;
        }


        @Override
        public boolean isBootCompleted() {
            return false;
        }

        @Override
        public boolean bootResourse2USB() {
            Log.i(TAG, "bootResourse2USB   ");
            ThirdParty.setRootSeek("busybox cp  -rf /data/local/user_logo  " + TCL.getUSBMountPath(ctx) + "/database/");
            return true;
        }

        @Override
        public void syncNetTime() {
            Settings.Global.putInt(ctx.getContentResolver(), Settings.Global.AUTO_TIME, 0);
            Settings.Global.putInt(ctx.getContentResolver(), Settings.Global.AUTO_TIME, 1);
        }

        @Override
        public void clearPatchBootanimation() {
        }

        @Override
        public void activeKeyByKeycode(boolean enable, int key) {
            String mun = SystemProperties.get("SHIELDKEYBUFFERNUM", "10");
            Log.i(TAG, "activeKey() isActive = " + enable + ",shuxing = " + mun + ",key " + key);
            WindowManager windowManager = new WindowManager(ctx);
            windowManager.activeKeyByKeycode(key, enable);
        }

        @Override
        public String getModelName() {
            return ThirdParty.getProjectName();
        }

        @Override
        public String getClientType() throws RemoteException {
            return TDeviceInfo.getInstance().getClientType(getProjectID());
        }

        @Override
        public int getProjectID() throws RemoteException {
            return TV.readV(TVDefine.ProjectID);
        }

        @Override
        public void setTvReturnKeyEnable(boolean enable) {
            if (enable) {
                SystemProperties.set(defs.PERSIST_HOTEL_EXITTV, String.valueOf(1));
            } else {
                SystemProperties.set(defs.PERSIST_HOTEL_EXITTV, String.valueOf(0));
            }
        }

        @Override
        public boolean getTvReturnKeyEnable() {
            int value = Integer.parseInt(SystemProperties.get(defs.PERSIST_HOTEL_EXITTV, "0"));
            return value == 1;
        }

        @Override
        public String[] getLaunchersList() {
            return mLauncherHelper.getLaunchersList();
        }

        @Override
        public boolean setScreenDisplay(boolean value) {
            int flag = SystemProperties.getInt(defs.PERSIST_FASTPOWER, 0);
            if (flag != 2) {
                return false;
            }
            if (value) {
                TTvFunctionManager.getInstance(ctx).setPowerBacklight(true);
                android.media.AudioManager audioManager = (android.media.AudioManager) getSystemService(Context.AUDIO_SERVICE);
                audioManager.setStreamMute(AudioManager.STREAM_MUSIC, false);
            } else {
                TTvFunctionManager.getInstance(ctx).setPowerBacklight(false);
                android.media.AudioManager audioManager = (android.media.AudioManager) getSystemService(Context.AUDIO_SERVICE);
                audioManager.setStreamMute(AudioManager.STREAM_MUSIC, true);
            }

            SystemProperties.set("persist.sys.curpowerstatus", value ? "true" : "false");
            return true;
        }

        @Override
        public boolean installPackage(String path, final IAppObserver observer) {
            if (packageManager != null) {
                packageManager = new MyPackageManager(ctx);
            }
            boolean ret = packageManager.installPackage(path, new MyPackageManager.IAppObserver() {
                @Override
                public void onPackageInstalled(String packageName,
                                               int returnCode, String message) {
                    try {
                        if (observer != null) {
                            observer.onPackageInstalled(packageName, returnCode, message);
                        } else {
                            Log.i(TAG, "observer is null");
                        }
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onPackageDeleted(String packageName,
                                             int returnCode, String msg) {
                    try {
                        observer.onPackageDeleted(packageName, returnCode, msg);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            });
            return ret;
        }

        @Override
        public boolean uninstallPackage(String packageStr, final IAppObserver observer) {
            if (packageManager != null) {
                packageManager = new MyPackageManager(ctx);
            }
            packageManager.deletePackage(packageStr, new MyPackageManager.IAppObserver() {
                @Override
                public void onPackageInstalled(String packageName,
                                               int returnCode, String message) {
                    try {
                        observer.onPackageInstalled(packageName, returnCode, message);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onPackageDeleted(String packageName,
                                             int returnCode, String msg) {
                    try {
                        observer.onPackageDeleted(packageName, returnCode, msg);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            });
            return true;
        }

        @Override
        public boolean setScreenOrientation(int value) {
            return false;
        }

        @Override
        public boolean verifyOTA(String path, final IOTAProgressListener listener) {
            if (path == null) {
                Log.i("ota", "path is null");
                if (listener != null) {
                    try {
                        listener.onFinish(false, "ota package is null");
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
                return false;
            }
            File otaFile = new File(path);
            if (!otaFile.exists() || !otaFile.canRead()) {
                Log.i("ota", "file is not exist or can not read");
                if (listener != null) {
                    try {
                        listener.onFinish(false, "ota package is not exist or can not read");
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
                return false;
            }
            try {
                RecoverySystem.verifyPackage(otaFile, progress -> {
                    if (listener != null) {
                        try {
                            listener.onProgress(progress);
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    }
                }, null);
                if (listener != null) {
                    try {
                        listener.onFinish(true, "verify ota package success");
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
                return true;
            } catch (IOException | GeneralSecurityException e) {
                e.printStackTrace();
                if (listener != null) {
                    try {
                        listener.onFinish(false, e.getMessage());
                    } catch (RemoteException e2) {
                        e2.printStackTrace();
                    }
                }
            }

            return false;
        }

        @Override
        public boolean installOTA(String path) {
            if (path == null) {
                Log.i("ota", "path is null");
                return false;
            }
            File otaFile = new File(path);
            if (!otaFile.exists() || !otaFile.canRead()) {
                Log.i("ota", "file is not exist or can not read");
                return false;
            }
            try {
                RecoverySystem.installPackage(getApplicationContext(), otaFile);
                return true;
            } catch (IOException e) {
                e.printStackTrace();
            }
            return false;
        }

        @Override
        public String getOtaVersion() {
            return getHotelOtaVersion();
        }

        @Override
        public void setProjectId(String password, int projectId) {
            if (!defs.SET_PROJECT_PASSWORD.equals(password)) {
                Log.i("api", "passwrod is error");
                return;
            }
            Log.i("api", "ProjectID is " + projectId);
            TV.writeV(TVDefine.ProjectID, projectId);
        }

        @Override
        public int getPictureProportion() {
            EnTCLAspectRatio ratio = TPictureManager.getInstance(ctx).getAspectRatio();
            Log.i("api", "ratio," + ratio.toString());
            int pictureProportion = 0;
            switch (ratio) {
                case EN_TCL_14X9:
                    pictureProportion = 0;
                    break;
                case EN_TCL_14X9_ZOOM:
                    pictureProportion = 1;
                    break;
                case EN_TCL_16X9:
                    pictureProportion = 2;
                    break;
                case EN_TCL_16X9_ZOOM:
                    pictureProportion = 3;
                    break;
                case EN_TCL_4X3:
                    pictureProportion = 4;
                    break;
                case EN_TCL_AUTO:
                    pictureProportion = 5;
                    break;
                case EN_TCL_CINERAMA:
                    pictureProportion = 6;
                    break;
                case EN_TCL_DOT_BY_DOT:
                    pictureProportion = 7;
                    break;
                case EN_TCL_MAX:
                    pictureProportion = 8;
                    break;
                case EN_TCL_NATIVE:
                    pictureProportion = 9;
                    break;
                case EN_TCL_STRETCH_ZOOM:
                    pictureProportion = 10;
                    break;
                case EN_TCL_SUPERLIVE:
                    pictureProportion = 11;
                    break;
                case EN_TCL_WIDE_ZOOM:
                    pictureProportion = 12;
                    break;
                case EN_TCL_WIDE_ZOOM2:
                    pictureProportion = 13;
                    break;
                case EN_TCL_ZOOM_2:
                    pictureProportion = 14;
                    break;
            }
            return pictureProportion;
        }

        @Override
        public String getUSBPermit() {
            return SystemProperties.get(DEFS.USB_PERMIT);
        }

        @Override
        public void setUSBPermit(boolean value) {
            SystemProperties.set(DEFS.USB_PERMIT, String.valueOf(value));
        }

        @Override
        public int getGraphicBacklight() {
            int value = TV.readV(TVDefine.GraphicBackLight);
            Log.i(TAG, "getGraphicBacklight  " + value);
            return value;
        }

        @Override
        public void setGraphicBacklight(int value) {
            Log.i(TAG, "setGraphicBacklight  " + value);
            TV.writeV(TVDefine.GraphicBackLight, value);
        }

        @Override
        public boolean setRtcWakeup(int year, int month, int day, int week, int hour, int minute, int second) {
            Log.i(TAG, "year " + year + ",month " + month + ",day " + day + ",week " + week + ",hour " + hour + ",minute " + minute + ",second " + second);
            rtcTimeHelper.setData(year, month, day, hour, minute, second);
            if (!rtcTimeHelper.isValid()) {
                Log.i(TAG, "time is not valid");
                return false;
            }

            Calendar mCalendar = Calendar.getInstance();
            Log.i("time_set", "set time:" + year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second);
            mCalendar.set(year, month - 1, day, hour, minute, second);
            long time = mCalendar.getTimeInMillis() - TimeZone.getDefault().getRawOffset();
            mCalendar.setTimeInMillis(time);
            int wDay = mCalendar.get(Calendar.DAY_OF_WEEK);
            final String SERVICE_RTC = "rtc";
            try {
                IRtcService iRtcService = IRtcService.Stub.asInterface(ServiceManager.getService(SERVICE_RTC));
                int ret = iRtcService.setAlarmWakeupTime(mCalendar.get(Calendar.YEAR),
                        mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH),
                        mCalendar.get(Calendar.DAY_OF_WEEK) - 1, mCalendar.get(Calendar.HOUR_OF_DAY),
                        mCalendar.get(Calendar.MINUTE), mCalendar.get(Calendar.SECOND));
                if (ret == 0) {
                    double retTime = iRtcService.getRTCSysTime();
                    Log.i("time_set", "set time---->" + time);
                    return true;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return false;
        }

        @Override
        public boolean setRtcTime(int year, int month, int day, int week, int hour, int minute, int second) {
            Log.i(TAG, "year " + year + ",month " + month + ",day " + day + ",week " + week + ",hour " + hour + ",minute " + minute + ",second " + second);
            rtcTimeHelper.setData(year, month, day, hour, minute, second);
            if (!rtcTimeHelper.isValid()) {
                Log.i(TAG, "time is not valid");
                return false;
            }

            Calendar mCalendar = Calendar.getInstance();
            Log.i("time_set", "set time:" + year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second);
            mCalendar.set(year, month - 1, day, hour, minute, second);
            long time = mCalendar.getTimeInMillis() - TimeZone.getDefault().getRawOffset();
            mCalendar.setTimeInMillis(time);
            int wDay = mCalendar.get(Calendar.DAY_OF_WEEK);
            final String SERVICE_RTC = "rtc";
            try {
                IRtcService iRtcService = IRtcService.Stub.asInterface(ServiceManager.getService(SERVICE_RTC));
                int ret = iRtcService.setRTCSysTime(mCalendar.get(Calendar.YEAR),
                        mCalendar.get(Calendar.MONTH) + 1, mCalendar.get(Calendar.DAY_OF_MONTH),
                        mCalendar.get(Calendar.DAY_OF_WEEK) - 1, mCalendar.get(Calendar.HOUR_OF_DAY),
                        mCalendar.get(Calendar.MINUTE), mCalendar.get(Calendar.SECOND));
                if (ret == 0) {
                    double retTime = iRtcService.getRTCSysTime();
                    Log.i("time_set", "set time---->" + time);
//		    			rtcTimeHelper.setSysDateTime();
//		                Log.i(TAG, "new time:" + new Date().toString());
                    return true;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return false;
        }

        @Override
        public void disableRtcWakeup() {
            rtcTimeHelper.disableRtcWakeup();
        }

        @Override
        public double getAlarmTime() {
            return rtcTimeHelper.getAlarmTime();
        }

        @Override
        public boolean sourceDetect(String sourceName) {
            Log.i(TAG, "sourceDetect " + sourceName);
            return ThirdParty.isSignalSource(sourceName);
        }

        @Override
        public boolean setAutoSelect(int value) {
            Log.i(TAG, "setAutoSelect " + value);
            switch (value) {
                case defs.AUTO_SELECT_OFF:
                case defs.AUTO_SELECT_MANUAL:
                case defs.AUTO_SELECT_AUTO:
                    Settings.System.putInt(ctx.getContentResolver(), "AUTO_SELECT_FLAG", value);
                    return true;
                default:
                    return false;
            }
        }

        @Override
        public int getAutoSelect() {
            Log.i(TAG, "getAutoSelect");
            try {
                return Settings.System.getInt(ctx.getContentResolver(), "AUTO_SELECT_FLAG");
            } catch (SettingNotFoundException e) {
                Log.i(TAG, "getAutoSelect SettingNotFoundException");
                e.printStackTrace();
            }
            return 0;
        }

        @Override
        public double getRTCSysTime() {
            return rtcTimeHelper.getRtcTime();
        }

        @Override
        public boolean setGPIO(int index, int value) {
            return mGpioHelper.setGPIO(index, value);
        }

        @Override
        public void activeKeyByKeycodeList(boolean enable, List<String> key, String className, String packageName) {
            ComponentName componentName = new ComponentName(className, packageName);
            int num = key.size() + 1;
            int count = 0;
            int[] keyCodeList = new int[num];
            for (String str : key) {
                keyCodeList[count] = Integer.parseInt(str);
                count++;
            }
            Log.i(TAG, "activeKey() isActive = " + enable + ",shuxing = " + key.toString());
            WindowManager windowManager = new WindowManager(ctx);
            windowManager.activeKeyByKeycodeCnPn(num, keyCodeList, enable, componentName, null);
        }

    }

//************************************频道数据处理<--------------------

    public List<String> getLaucherList() {
        PackageManager pm = ctx.getPackageManager();
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
//		mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        mainIntent.addCategory(Intent.CATEGORY_HOME);
        List<ResolveInfo> mResolveInfo = pm.queryIntentActivities(mainIntent, 0);
        ApplicationInfo info;
        //ADD zzly :TCL LAUNCHER /TV /HiHotel
        List<String> lstPackage = new ArrayList<String>();
        lstPackage.add(defs.PERSIST_DEFAULT_LAUNCHER);
        lstPackage.add(defs.PERSIST_LAUNCHER_TV);

        for (ResolveInfo resolveInfo : mResolveInfo) {
            String packName = resolveInfo.activityInfo.packageName;
            if (lstPackage.contains(packName)) {
                continue;
            }
            lstPackage.add(packName);
        }

        return lstPackage;
    }

    public String handleSourceData(int value) {
        String str = ATV;
        switch (value) {
            case DEFS.HOTEL_SOURCE_VGA:
                str = VGA;
                break;
            case DEFS.HOTEL_SOURCE_ATV:
                str = ATV;
                break;
            case DEFS.HOTEL_SOURCE_AV2:
                str = AV;
                break;
            case DEFS.HOTEL_SOURCE_HDMI1:
                str = HDMI;
                break;
            case DEFS.HOTEL_SOURCE_HDMI2:
                str = HDMI2;
                break;
            case DEFS.HOTEL_SOURCE_HDMI3:
                str = HDMI3;
                break;
            case DEFS.HOTEL_SOURCE_HDMI4:
                str = HDMI4;
                break;
            case DEFS.HOTEL_SOURCE_DTV:
                str = DTV;
                break;
            case DEFS.HOTEL_SOURCE_STORAGE:
                str = STROAGE;
            default:
                break;
        }
        return str;
    }


    public int handleSourceDataToSave(String value) {
        int str = 0;
        if (value.equals(ATV)) {
            str = DEFS.HOTEL_SOURCE_ATV;
        } else if (value.equals(DTV)) {
            str = DEFS.HOTEL_SOURCE_DTV;
        } else if (value.equals(AV)) {
            str = DEFS.HOTEL_SOURCE_AV2;
        } else if (value.equals(HDMI)) {
            str = DEFS.HOTEL_SOURCE_HDMI1;
        } else if (value.equals(HDMI2)) {
            str = DEFS.HOTEL_SOURCE_HDMI2;
        } else if (value.equals(HDMI3)) {
            str = DEFS.HOTEL_SOURCE_HDMI3;
        } else if (value.equals(HDMI4)) {
            str = DEFS.HOTEL_SOURCE_HDMI4;
        } else if (value.equals(VGA)) {
            str = DEFS.HOTEL_SOURCE_VGA;
        } else if ((value.equals(STROAGE))) {
            str = DEFS.HOTEL_SOURCE_STORAGE;
        }
        return str;
    }

    public String handlePathStr(String path) {
        String str = path;
        if (path != null && str.contains("/")) {
            int endindex = str.lastIndexOf("/");
            str = str.substring(0, endindex) + "/";
        } else {
            str = "";
        }
        Log.i(TAG, "handlePathStr str " + str);
        return str;
    }

    //{"ATV","DTV","SCART","AV1","YPBPR","VGA","HDMI1","HDMI2","HDMI3","HDMI4"}; 多媒体命名规则<<----------------
    public static final String ATV = "ATV";
    public static final String DTV = "DTV";
    public static final String VGA = "VGA";
    public static final String HDMI = "HDMI";
    public static final String HDMI1 = "HDMI1";
    public static final String HDMI2 = "HDMI2";
    public static final String HDMI3 = "HDMI3";
    public static final String HDMI4 = "HDMI4";
    public static final String AV = "AV";
    public static final String STROAGE = "STROAGE";
    public static final String STROAGE1 = "STORAGE";


    private static final String MSG_SETTING_LOGO_OK = "com.tcl.customerapi.loadlogo.ok";
    private static final String MSG_SETTING_LOGO_ERR = "com.tcl.customerapi.loadlogo.err";
    private static final String MSG_SETTING_BOOTANIMATION_OK = "com.tcl.customerapi.loadbootanimation.ok";
    private static final String MSG_SETTING_BOOTANIMATION_ERR = "com.tcl.customerapi.loadbootanimation.err";
    private static final String MSG_SETTING_VIDEO_OK = "com.tcl.customerapi.loadvideo.ok";
    private static final String MSG_SETTING_VIDEO_ERR = "com.tcl.customerapi.loadvideo.err";

    private static final String MSG_SETTING_ERR = "com.tcl.customerapi.settings.err";
    private static final String MSG_SETTING_OK = "com.tcl.customerapi.settings.ok";

    private void sendBroadCast(String msg) {
        Intent intent = new Intent();
        intent.setAction(msg);
        sendBroadcast(intent);
    }

    public boolean setHotelCecDevicePowerOff(boolean flag) {
        CecConfigInfo mRet = mTvCecManager.getCecConfiguration();
        if (mRet == null) {
            return false;
        }
        mRet.deviceAutoPowerOn = flag;
        mTvCecManager.setCecConfiguration(mRet);
        return true;
    }

    public boolean getHotelCecDevicePowerOff() {
        CecConfigInfo mRet = mTvCecManager.getCecConfiguration();
        if (mRet == null) {
            return false;
        }
        return mRet.deviceAutoPowerOn;
    }

    public TTvCecManager mTvCecManager;

    public void sendKeyThread(final int keycode) {
        new Thread(() -> sendKey(keycode)).start();
    }

    public boolean sendKey(int keycode) {
        try {
            Instrumentation inst = new Instrumentation();
            inst.sendKeyDownUpSync(keycode);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    //		public static final String oatFilePath = "/data/hotel_source/tcl_oatfile";
    public boolean updateOtaData() {
        try {
            if (FileUtil.isFile(defs.otaFilePath)) {
                List<String> oat = FileUtil.readLineFile(defs.otaFilePath);
                if (oat == null || oat.size() == 0 || oat.size() == 1) {

                    FileUtil.deleteFile(defs.otaFilePath);
                    return false;
                }
                if (!oat.get(0).equals(defs.otaFilename)) {

                    FileUtil.deleteFile(defs.otaFilePath);
                    return false;
                }
                int size = oat.size();
                for (int i = 1; i < size; i++) {

                    Log.i(TAG, "	" + oat.get(i));
                    String[] str = oat.get(i).split("=");
                    if (str.length != 2) {
                        FileUtil.deleteFile(defs.otaFilePath);
                        return false;
                    }
                    if (str[0].trim().equals("logo") && (str[1].trim().equals("2"))) {
                        //set user display
                        ThirdParty.mFactoryAdapter.setHotelBootLogo(2);

                        if (FileUtil.isFile(defs.userVideo) && FileUtil.isFile(defs.userVideoINI)) {
                            Log.i(TAG, "start copy userVideo");
                            ThirdParty.setLogoApi(defs.LOGO_FILE_PATH);
                            ThirdParty.setVideoApi(defs.LOGO_FILE_PATH);

                            ThirdParty.setHotelBootVideo(1);
                        }
                        Log.i(TAG, "logo	" + "ok");

                    } else if (str[0].trim().equals("logo") && (str[1].trim().equals("1"))) {
                        //set user display
                        ThirdParty.mFactoryAdapter.setHotelBootLogo(2);

                        if (FileUtil.isFile(defs.userBootanimation)) {
                            Log.i(TAG, "start copy userBootanimation");
                            ThirdParty.setLogoApi(defs.LOGO_FILE_PATH);
                            ThirdParty.setUserBootAnimation(defs.LOGO_FILE_PATH);
                            myIBinder.setPowerOnAdbootanimation(defs.LOGO_FILE_PATH + "adbootanimation.zip");
                            myIBinder.setPowerOnAnimtemplet(defs.LOGO_FILE_PATH + "animtemplet.zip");
                            ThirdParty.setHotelBootAnimation(2);
                        }
                        Log.i(TAG, "logo	" + "ok");

                    } else if (str[0].trim().equals("tvmode") && str[1].trim().equals("1")) {

//							SystemProperties.set(defs.PERSIST_TVMODE, 1+"");
//							ThirdParty.mFactoryAdapter.setHotelFlag(1);
//							ThirdParty.mFactoryAdapter.setHotelAttribute(FactoryManager.FACTORY_ATTR_HOTEL_AUTO_SET, 1);
                        myIBinder.setHotelMode(1);
                        int boot_logo_mode = ThirdParty.mFactoryAdapter.getHotelBootLogo();
                        if (boot_logo_mode != DEFS.HOTEL_DEFAULT_LOGO) {
                            ThirdParty.mFactoryAdapter.setHotelBootLogo(boot_logo_mode);
                        }

                        //取消十五秒待机
                        Log.i(TAG, "set persist.sys.standbymode 0");
                        SystemProperties.set(defs.PERSIST_STANDBY_MODE, defs.SHUT_DOWN_STATE_OFF);

                        SystemProperties.set(defs.PERSIST_FACTORY_HOTEL_FLAG, "1");
                        Log.i(TAG, "tvmode	" + "ok");
                    } else if (str[0].trim().equals("launchername") && !str[1].trim().equals("")) {
                        String cmd = "pm enable " + str[1].trim();
                        boolean ret = ThirdParty.setRootSeek(cmd);
                        Log.i(TAG, "enable app ret	" + ret);
                        SystemProperties.set(defs.PERSIST_LAUNCHER_NAME, str[1].trim());
                        myIBinder.setLauncher(str[1].trim());
//                        int inputSource = InputDevice.SOURCE_KEYBOARD;
//                        sendKeyEvent(inputSource, KeyEvent.KEYCODE_HOME);//注入Home事件，立即切换Launcher
                        myIBinder.simulateKeyboard(KeyEvent.KEYCODE_HOME);
                        openApp(str[1].trim(), ctx);
//							int value = mLauncherHelper.getUserLauncherId(str[1].trim());
//							if(value!=-1){
//								mLauncherHelper.setLauncher(value);
//
//								Intent it = new Intent(Intent.ACTION_MAIN);
////								it.addCategory(Intent.CATEGORY_LAUNCHER);
//								it.setPackage("com.ts.launcher");
//								PackageManager pm = this.getPackageManager();
//								List<ResolveInfo> ra = pm.queryIntentActivities(it, 0);
//								if(ra!=null && ra.size()>0){
//									Log.i(TAG , "ResolveInfo  "+ra.get(0).activityInfo.packageName);
//									Log.i(TAG , "ResolveInfo  "+ra.get(0).activityInfo.name);
//
//									boolean ret1 = ThirdParty.setHotelLauncherAppName(ra.get(0).activityInfo.packageName);
//									boolean ret2 = ThirdParty.setHotelLauncherActivityName(ra.get(0).activityInfo.name);
//									if(ret1 && ret2){
//										Log.i(TAG , "set HotelLauncherApp is ok ");
//									}
//								}
//							}
                        Log.i(TAG, "launchername	" + str[1].trim());

                    } else if (str[0].trim().equals("openAtv") && str[1].trim().equals("1")) {
                        Log.i("api", "open atv");
                        openEnergyState(1);
                    } else if (str[0].trim().equals("closeShotDialog") && str[1].trim().equals("1")) {
                        //取消十五秒待机
                        Log.i(TAG, "set persist.sys.standbymode 1");
                        SystemProperties.set(defs.PERSIST_STANDBY_MODE, defs.SHUT_DOWN_STATE_ON);
                    } else if (str[0].trim().equals("installapk") && str[1].trim().equals("1")) {

                        SystemProperties.set(defs.PERSIST_DEBUG_INSTALLAPK, 1 + "");
                        Log.i(TAG, "installapk 	" + "ok");
                    }
                }
                FileUtil.deleteFile(defs.otaFilePath);
                return true;
            }
            Log.i(TAG, "	no tcl_oatfile");
            FileUtil.deleteFile(defs.otaFilePath);
            return false;
        } catch (Exception e) {
            Log.i(TAG, "Exception oatFilePath	");
            FileUtil.deleteFile(defs.otaFilePath);
            return false;
        }
    }

    private void setLauncher() {
        try {
            String launcherName = myIBinder.getLauncher();
            if (launcherName == null || launcherName.equals("")) {
                return;
            }
            myIBinder.setHotelMode(1);
            int boot_logo_mode = ThirdParty.mFactoryAdapter.getHotelBootLogo();
            if (boot_logo_mode != DEFS.HOTEL_DEFAULT_LOGO) {
                ThirdParty.mFactoryAdapter.setHotelBootLogo(boot_logo_mode);
            }
            //取消十五秒待机
            Log.i(TAG, "set persist.sys.standbymode 0");
            SystemProperties.set(defs.PERSIST_STANDBY_MODE, defs.SHUT_DOWN_STATE_OFF);

            SystemProperties.set(defs.PERSIST_FACTORY_HOTEL_FLAG, "1");
            Log.i(TAG, "tvmode	" + "ok launcherName " + launcherName);

            SystemProperties.set(defs.PERSIST_LAUNCHER_NAME, launcherName);
            myIBinder.setLauncher(launcherName);
            myIBinder.simulateKeyboard(KeyEvent.KEYCODE_HOME);
            openApp(launcherName, ctx);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void sendKeyEvent(int inputSource, int keyCode) {
        new Thread(() -> {
            Log.i(TAG, "sendKeyEvent " + keyCode);
            long now = SystemClock.uptimeMillis();
            injectKeyEvent(new KeyEvent(now, now, KeyEvent.ACTION_DOWN, keyCode, 0, 0,
                    KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0, inputSource));

            injectKeyEvent(new KeyEvent(now, now, KeyEvent.ACTION_UP, keyCode, 0, 0,
                    KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0, inputSource));
        }).start();
    }

    private void injectKeyEvent(KeyEvent event) {
        Log.i(TAG, "injectKeyEvent: " + event);
//	        InputManager.getInstance().injectInputEvent(event,
//	                InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH);
        sendKey(event.getKeyCode());
    }

    public String getHostIP() {
        String hostIp = null;
        try {
            Enumeration nis = NetworkInterface.getNetworkInterfaces();
            InetAddress ia = null;
            while (nis.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface) nis.nextElement();
                Enumeration<InetAddress> ias = ni.getInetAddresses();
                while (ias.hasMoreElements()) {
                    ia = ias.nextElement();
                    if (ia instanceof Inet6Address) {
                        continue;// skip ipv6
                    }
                    String ip = ia.getHostAddress();
                    if (!"127.0.0.1".equals(ip)) {
                        hostIp = ia.getHostAddress();
                        break;
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return hostIp;

    }

    public String getHotelOtaVersion() {
        final String defaultHotelVersionFile = "/system/hotel_version.txt";
        final String firstHotelVersionFile = "/product/hotel_version.txt";

        String version = getOtaVersionStr(firstHotelVersionFile);
        if (version == null || version.trim().length() == 0) {
            version = getOtaVersionStr(defaultHotelVersionFile);
        }
        return version;
    }

    public String getOtaVersionStr(final String hotelVersionFile) {
        final String versionPram = "version";
        File file = new File(hotelVersionFile);
        if (!file.exists() || !file.canRead()) {
            return "";
        }
        MyPropterties propterties = new MyPropterties(hotelVersionFile);
        return propterties.getProperty(versionPram);
    }

    public void openApp(String packageName, Context context) {
        PackageManager packageManager = context.getPackageManager();
        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        resolveIntent.setPackage(packageName);

        List<ResolveInfo> apps = packageManager.queryIntentActivities(
                resolveIntent, 0);

        ResolveInfo ri = apps.iterator().next();
        if (ri != null) {
            String className = ri.activityInfo.name;

            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            ComponentName cn = new ComponentName(packageName, className);

            Log.i(TAG, "packageName " + packageName + " className" + className);
            intent.setComponent(cn);
            context.startActivity(intent);
        }
    }

    private void openEnergyState(int isCloseShotDialog) {
        int projectId;
        try {
            projectId = myIBinder.getProjectID();
            Log.i(TAG, "projectId," + projectId);
            if (projectId > DEFS.PROJECT_FLAG) {
                Log.i(TAG, "ATV already open");
                return;
            }
            projectId = projectId + DEFS.PROJECT_FLAG;
            Log.i(TAG, "new projectId," + projectId);
            List<String> projectIdList = FileUtil.readSettingConfig(DEFS.PROJECT_FILE_NAME);
            if (projectIdList == null || projectIdList.isEmpty()) {
                Log.i(TAG, "projectIdList is null");
                return;
            }
            if (projectIdList.contains("MODEL_" + projectId)) {
                myIBinder.setProjectId("1950", projectId);
                try {
                    Thread.sleep(6 * 1000);
                    if (isCloseShotDialog == 2) {
                        Log.i(TAG, "set persist.sys.standbymode 1");
                        SystemProperties.set(defs.PERSIST_STANDBY_MODE, defs.SHUT_DOWN_STATE_ON);
                    }
                    myIBinder.rebootSystem();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else {
                Log.i(TAG, "set project id fail,not find PID " + projectId);
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    void sendSystemModeChangerBroadcast() {
        Log.i(TAG, "send system mode change broadcast to system");
        Intent systemModeChanageIntent = new Intent(defs.ACTION_HOTEL_MODE_CHANGED);
        systemModeChanageIntent.setPackage("com.android.systemservice");
        ctx.sendBroadcast(systemModeChanageIntent);
    }
}
