package com.datarecovery.master.module.main;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.atmob.app.lib.base.BaseActivity;
import com.datarecovery.master.R;
import com.datarecovery.master.data.consts.AdFuncId;
import com.datarecovery.master.data.consts.EventId;
import com.datarecovery.master.databinding.ActivityMainBinding;
import com.datarecovery.master.databinding.ItemMainTabLayoutBinding;
import com.datarecovery.master.handler.EventHelper;
import com.datarecovery.master.module.audiorecover.AudioRecoverActivity;
import com.datarecovery.master.module.example.ExampleFragment;
import com.datarecovery.master.module.filerecover.FileRecoverActivity;
import com.datarecovery.master.module.homepage.HomePageFragment;
import com.datarecovery.master.module.imgrecover.ImageRecoverActivity;
import com.datarecovery.master.module.member.MemberType;
import com.datarecovery.master.module.mine.MineFragment;
import com.datarecovery.master.module.videorecover.VideoRecoverActivity;
import com.datarecovery.master.sdk.ad.AtmobAdHelper;
import com.datarecovery.master.sdk.ad.InterstitialListenerAdapter;
import com.datarecovery.master.utils.ToastUtil;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import dagger.hilt.android.AndroidEntryPoint;


@AndroidEntryPoint
public class MainActivity extends BaseActivity<ActivityMainBinding> {


    private static final String MEMBER_TYPE = "member_type";
    private MainViewModel mainViewModel;
    private TabLayoutMediator tabLayoutMediator;
    private MainPagerAdapter mainPagerAdapter;
    private long mExitTime;

    public static void start(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    public static void startToTargetActivity(Context context, @MemberType String memberType) {
        Intent intent = new Intent(context, MainActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.putExtra(MEMBER_TYPE, memberType);
        context.startActivity(intent);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null) {
            String targetType = intent.getStringExtra(MEMBER_TYPE);
            if (targetType != null) {
                switch (targetType) {
                    case MemberType.APP_IMAGE_RECOVER:
                        ImageRecoverActivity.start(this, MemberType.APP_IMAGE_RECOVER);
                        break;
                    case MemberType.APP_FILE_RECOVER:
                        FileRecoverActivity.start(this);
                        break;
                    case MemberType.APP_VIDEO_RECOVER:
                        VideoRecoverActivity.start(this);
                        break;
                    case MemberType.APP_AUDIO_RECOVER:
                        AudioRecoverActivity.start(this);
                        break;
                    case MemberType.APP_IMAGE_CLEAN:
                        ImageRecoverActivity.start(this, MemberType.APP_IMAGE_CLEAN);
                        break;
                }
            }
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        loadLaunchAd();
    }

    private void loadLaunchAd() {
        AtmobAdHelper.showInterstitial(AdFuncId.INTERSTITIAL_HOME_ENTER, new InterstitialListenerAdapter() {
            @Override
            public void onClose() {
                super.onClose();
                AtmobAdHelper.showInterstitial(AdFuncId.INTERSTITIAL_HOME_ENTER_2, null);
            }

            @Override
            public void onFail(String s) {
                super.onFail(s);
                AtmobAdHelper.showInterstitial(AdFuncId.INTERSTITIAL_HOME_ENTER_2, null);
            }
        });
    }

    private void initView() {
        initViewPager();
        initTabLayout();
    }

    private void initViewPager() {
        mainPagerAdapter = new MainPagerAdapter(this);
        binding.mainViewPager.setAdapter(mainPagerAdapter);
        binding.mainViewPager.setUserInputEnabled(false);
        binding.mainViewPager.setOffscreenPageLimit(mainPagerAdapter.getItemCount());
    }

    private void initTabLayout() {
        binding.mainTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            boolean isInitial = true;

            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                ItemMainTabLayoutBinding itemBinding = (ItemMainTabLayoutBinding) tab.getTag();
                if (itemBinding != null) {
                    itemBinding.tabText.setSelected(true);
                    itemBinding.tabIcon.setSelected(true);
                }
                Class<? extends Fragment> pagerClass = mainPagerAdapter.getMainPagerItemByPosition(tab.getPosition()).getPagerClass();
                if (pagerClass.equals(HomePageFragment.class)) {
                    if (!isInitial) {
                        EventHelper.report(EventId.EVENT_3000400);
                    }
                } else if (pagerClass.equals(ExampleFragment.class)) {
                    AtmobAdHelper.showInterstitial(AdFuncId.INTERSTITIAL_CASE, null);
                    if (!isInitial) {
                        EventHelper.report(EventId.EVENT_3010000);
                    }
                } else if (pagerClass.equals(MineFragment.class)) {
                    AtmobAdHelper.showInterstitial(AdFuncId.INTERSTITIAL_MINE, null);
                    if (!isInitial) {
                        EventHelper.report(EventId.EVENT_3020000);
                    }
                }
                isInitial = false;
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                ItemMainTabLayoutBinding itemBinding = (ItemMainTabLayoutBinding) tab.getTag();
                if (itemBinding != null) {
                    itemBinding.tabText.setSelected(false);
                    itemBinding.tabIcon.setSelected(false);
                }
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        tabLayoutMediator = new TabLayoutMediator(binding.mainTabLayout, binding.mainViewPager, true, false, (tab, position) -> {
            MainPagerAdapter.MainPagerItem mainPagerItem = mainPagerAdapter.getMainPagerItemByPosition(position);
            ItemMainTabLayoutBinding itemBinding = ItemMainTabLayoutBinding.inflate(getLayoutInflater());
            itemBinding.tabText.setText(mainPagerItem.getTabName());
            itemBinding.tabIcon.setImageResource(mainPagerItem.getTabIcon());
            tab.setCustomView(itemBinding.getRoot());
            tab.setTag(itemBinding);
        });
        tabLayoutMediator.attach();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (tabLayoutMediator != null) {
            tabLayoutMediator.detach();
        }
    }

    @Override
    protected void initViewModel() {
        super.initViewModel();
        mainViewModel = getViewModelProvider().get(MainViewModel.class);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void exit() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            ToastUtil.show(R.string.exit_application_text, ToastUtil.LENGTH_LONG);
            mExitTime = System.currentTimeMillis();
        } else {
            try {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_HOME);
                startActivity(intent);
            } catch (Exception ignore) {
            }
        }
    }

    @Override
    protected boolean shouldImmersion() {
        return true;
    }
}
