package com.datarecovery.master.data.repositories;


import android.text.TextUtils;

import com.atmob.user.AtmobUser;
import com.datarecovery.master.BuildConfig;
import com.datarecovery.master.data.consts.ChannelId;
import com.datarecovery.master.module.member.MemberType;
import com.datarecovery.master.sdk.gravity.GravityHelper;
import com.datarecovery.master.utils.BoxingUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import javax.inject.Inject;
import javax.inject.Singleton;

@Singleton
public class ConfigRepository {

    private static boolean isOpenTrialMembership = false;

    private static final String[] trialMember = new String[]{
            MemberType.APP_IMAGE_RECOVER,
            MemberType.APP_FILE_RECOVER,
            MemberType.APP_VIDEO_RECOVER,
            MemberType.APP_AUDIO_RECOVER,
    };

    private static final List<String> trialMemberList = new ArrayList<>(Arrays.asList(trialMember));

    @Inject
    public ConfigRepository() {
        getTrialMembershipStatus();
    }


    private void getTrialMembershipStatus() {
        if (BuildConfig.DEBUG) {
            isOpenTrialMembership = true;
            return;
        }
        //先判断渠道，如果聚道推广，不管是什么商店都不开启试用会员
        GravityHelper.registerAttributionResultCallback(attributed -> {
            if (BoxingUtil.boxing(attributed)) {
                //归因成功
                isOpenTrialMembership = false;
                return;
            }
            if (AtmobUser.getAtmobTgPlatformId() != ChannelId.SD || TextUtils.isEmpty(AtmobUser.getAtmobChannel())) {
                isOpenTrialMembership = false;
                return;
            }
            if (!isTargetSuffixChannel(ChannelId.HUAWEI) &&
                    !isTargetSuffixChannel(ChannelId.HONOR) &&
                    !isTargetSuffixChannel(ChannelId.VIVO) &&
                    !isTargetSuffixChannel(ChannelId.XIAOMI)) {
                isOpenTrialMembership = false;
                return;
            }
            isOpenTrialMembership = true;
        });
    }


    public static boolean isTargetSuffixChannel(String targetChannel) {
        String atmobChannel = AtmobUser.getAtmobChannel();
        if (atmobChannel == null || targetChannel == null) {
            return false;
        }
        int index = atmobChannel.indexOf(targetChannel, atmobChannel.length() - targetChannel.length());
        return index != -1;
    }

    public static boolean isIsOpenTrialMembership() {
        return isOpenTrialMembership;
    }

    public static boolean isConformTrialAuths(@MemberType String auth) {
        if (!isOpenTrialMembership) {
            return false;
        }
        return isHaveTrialAuth(auth);
    }

    private static boolean isHaveTrialAuth(@MemberType String auth) {
        if (TextUtils.isEmpty(auth)) {
            return false;
        }
        return trialMemberList.contains(auth);
    }
}
