package com.uiui.zyappstore.network;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Environment;
import android.util.Log;

import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.tencent.android.tpush.XGIOperateCallback;
import com.tencent.android.tpush.XGPushManager;
import com.tencent.mmkv.MMKV;
import com.uiui.zyappstore.bean.AppClassBean;
import com.uiui.zyappstore.bean.AppInfo;
import com.uiui.zyappstore.bean.Banner;
import com.uiui.zyappstore.bean.BaseResponse;
import com.uiui.zyappstore.disklrucache.CacheHelper;
import com.uiui.zyappstore.network.api.AdminAppApi;
import com.uiui.zyappstore.network.api.AdminAppClassApi;
import com.uiui.zyappstore.network.api.BannerImage;
import com.uiui.zyappstore.network.api.ClassAppApi;
import com.uiui.zyappstore.network.api.DownloadApp;
import com.uiui.zyappstore.network.api.GetBanner;
import com.uiui.zyappstore.network.api.NewestAppUpdate;
import com.uiui.zyappstore.network.api.QueryAllApp;
import com.uiui.zyappstore.network.api.QueryPackageApp;
import com.uiui.zyappstore.network.api.SNInfo;
import com.uiui.zyappstore.network.api.SearchAdminAppApi;
import com.uiui.zyappstore.network.api.SearchAppApi;
import com.uiui.zyappstore.network.interceptor.RepeatRequestInterceptor;
import com.uiui.zyappstore.utils.JGYUtils;
import com.uiui.zyappstore.utils.Utils;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import okhttp3.Cache;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class NetInterfaceManager {
    @SuppressLint("StaticFieldLeak")
    private static NetInterfaceManager sInstance;
    private Context mContext;
    private Retrofit mRetrofit;
    private MMKV mMMKV = MMKV.defaultMMKV();
    private OkHttpClient okHttpClient;
    private CacheHelper cacheHelper;

    //超时时间
    private static final int timeOut = 5;
    // 缓存文件最大限制大小20M
    private static final long cacheSize = 1024 * 1024 * 64;
    public static final String CUSTOM_REPEAT_REQ_PROTOCOL = "MY_CUSTOM_REPEAT_REQ_PROTOCOL";
    public static final String HTTP_KEY = "YTM3YTAxNTJmMmZmNzkyM2E2YzIwZjlhZTc0NzNmMGI=";

    private NetInterfaceManager(Context context) {
        if (context == null) {
            throw new RuntimeException("Context is NULL");
        }
        this.mContext = context;
        this.cacheHelper = new CacheHelper(mContext);

        if (null == mRetrofit) {
            if (okHttpClient == null) {
                //如果无法生存缓存文件目录，检测权限使用已经加上，检测手机是否把文件读写权限禁止了
                OkHttpClient.Builder builder = new OkHttpClient.Builder();
                builder.connectTimeout(timeOut, TimeUnit.SECONDS); // 设置连接超时时间
                builder.writeTimeout(timeOut, TimeUnit.SECONDS);// 设置写入超时时间
                builder.readTimeout(timeOut, TimeUnit.SECONDS);// 设置读取数据超时时间
                builder.retryOnConnectionFailure(true);// 设置进行连接失败重试
                builder.addInterceptor(new RepeatRequestInterceptor());

                // 设置缓存文件路径
                String cacheDirectory = getCacheDir() + "/OkHttpCache";
                Cache cache = new Cache(new File(cacheDirectory), cacheSize);
                builder.cache(cache);// 设置缓存
                okHttpClient = builder.build();
            }

            mRetrofit = new Retrofit.Builder()
                    .client(okHttpClient)
                    .baseUrl(UrlAddress.ROOT_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                    .build();
        }
    }

    public static void init(Context context) {
        if (sInstance == null) {
            sInstance = new NetInterfaceManager(context);
        }
    }

    private String getCacheDir() {
        String cachePath;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            if (mContext.getExternalCacheDir() != null) {
                cachePath = mContext.getExternalCacheDir().getPath();
            } else if (mContext.getExternalFilesDir("cache") != null) {
                cachePath = mContext.getExternalFilesDir("cache").getPath();
            } else {
                cachePath = mContext.getCacheDir().getPath();
            }
        } else {
            cachePath = mContext.getCacheDir().getPath();
        }
        return cachePath;
    }

    public static NetInterfaceManager getInstance() {
        if (sInstance == null) {
            throw new IllegalStateException("You must be init NetworkManager first");
        }
        return sInstance;
    }


    public Observable<BaseResponse<Banner>> getBannerObservable() {
        return mRetrofit.create(GetBanner.class)
                .getBanner()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    public Observable<BaseResponse<List<AppInfo>>> getAdminAppObservable() {
        return mRetrofit.create(AdminAppApi.class).getAdminApp()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    public Observable<BaseResponse<List<AppInfo>>> getQueryAllAppObservable() {
        return mRetrofit.create(QueryAllApp.class)
                .getAllApp(Utils.getSerial())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    public Observable<BaseResponse<List<AppInfo>>> getAdminAppByClassObservable(int id) {
        return mRetrofit.create(ClassAppApi.class)
                .getAdminAppByClass(id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    public Observable<BaseResponse<List<AppClassBean>>> getAdminAppClassObservable() {
        return mRetrofit.create(AdminAppClassApi.class)
                .getAdminAppClassApi()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    public SNInfo getuserInfoControl() {
        return mRetrofit.create(SNInfo.class);
    }

    public SearchAppApi getSearchAppControl() {
        return mRetrofit.create(SearchAppApi.class);
    }

    public SearchAdminAppApi getSearchAdminAppControl() {
        return mRetrofit.create(SearchAdminAppApi.class);
    }

    public BannerImage getBannerImageControl() {
        return mRetrofit.create(BannerImage.class);
    }

    public DownloadApp getDownloadAppControl() {
        return mRetrofit.create(DownloadApp.class);
    }

    public NewestAppUpdate getNewestAppUpdateControl() {
        return mRetrofit.create(NewestAppUpdate.class);
    }

    public QueryPackageApp getQueryPackageAppControl() {
        return mRetrofit.create(QueryPackageApp.class);
    }

    public interface onCompleteCallback {
        void onComplete();
    }

    public void setPushTags(onCompleteCallback callback) {
        Set<String> set = new HashSet<>();
        JGYUtils.getInstance().getAppPlatform(platform -> {
            if (platform == JGYUtils.MTKPlatform) {
                set.add(JGYUtils.MTKTag);
            } else if (platform == JGYUtils.CubePlatform) {
                set.add(JGYUtils.ZhanruiTag);
            } else if (platform == JGYUtils.ZhanruiPlatform) {
                set.add(JGYUtils.NewZhanruiTag);
            } else if (platform == JGYUtils.UMTK11Platform) {
                set.add(JGYUtils.UMTK11Tag);
            } else if (platform == JGYUtils.UZY12Platform) {
                set.add(JGYUtils.UZY12Tag);
            } else if (platform == JGYUtils.Cube8183Platform) {
                set.add(JGYUtils.Cube8183Tag);
            }else if (platform == JGYUtils.Teclast8183Platform) {
                set.add(JGYUtils.TeclastMTK12Tag);
            }else if (platform == JGYUtils.ipaly50SEPlatform) {
                set.add(JGYUtils.ipaly50SETag);
            }
        });
        setpushTag(set);
        callback.onComplete();
    }

    private void setpushTag(Set<String> tagSets) {
        XGPushManager.clearAndAppendTags(mContext, "clearAndAppendTags :" + System.currentTimeMillis(), tagSets, new XGIOperateCallback() {
            @Override
            public void onSuccess(Object o, int i) {
                Log.e("setPushTags", "onSuccess: " + o);
            }

            @Override
            public void onFail(Object o, int i, String s) {
                Log.e("setPushTags", "onFail: " + o);
            }
        });
        String[] tag = new ArrayList<>(tagSets).toArray(new String[tagSets.size()]);
        CloudPushService pushService = PushServiceFactory.getCloudPushService();
        pushService.bindTag(CloudPushService.DEVICE_TARGET, tag, null, new CommonCallback() {
            @Override
            public void onSuccess(String s) {
                Log.e("bindTag","bind tag " + Arrays.toString(tag) + " success\n");
            }

            @Override
            public void onFailed(String errorCode, String errorMsg) {
                Log.e("bindTag","bind tag " + Arrays.toString(tag) + " failed." +
                        "errorCode: " + errorCode + ", errorMsg:" + errorMsg + "\n");
            }
        });
    }
}