package com.makeeasy.dpandstatus;

import static android.widget.Toast.LENGTH_SHORT;
import static android.widget.Toast.makeText;
import static com.makeeasy.dpandstatus.Constant.CONTACT_US_TEXT;
import static com.makeeasy.dpandstatus.Constant.POLICY_LINK;
import static com.makeeasy.dpandstatus.Constant.SHARE_TEXT;
import static com.makeeasy.dpandstatus.Constant.SHEETS;
import static com.makeeasy.dpandstatus.Constant.alertBox;
import static com.makeeasy.dpandstatus.Constant.getAdSize;

import android.content.Intent;
import android.content.IntentSender;
import android.net.Uri;
import android.os.Bundle;
import android.widget.FrameLayout;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.initialization.AdapterStatus;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.android.play.core.appupdate.AppUpdateInfo;
import com.google.android.play.core.appupdate.AppUpdateManager;
import com.google.android.play.core.appupdate.AppUpdateManagerFactory;
import com.google.android.play.core.install.model.AppUpdateType;
import com.google.android.play.core.install.model.UpdateAvailability;
import com.google.android.play.core.tasks.Task;
import com.makeeasy.dpandstatus.adapter.ViewPagerAdapter;
import com.makeeasy.dpandstatus.model.Category;
import com.makeeasy.dpandstatus.sheets.ExitSheet;

import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    private ExitSheet exitSheet;
    private DrawerLayout drawerLayout;
    public static List<Category> categoryList;
    private AppUpdateManager mAppUpdateManager;
    private static final int RC_APP_UPDATE = 11;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MobileAds.initialize(this, initializationStatus -> {
            Map<String, AdapterStatus> statusMap = initializationStatus.getAdapterStatusMap();
            for (String adapterClass : statusMap.keySet()) {
                AdapterStatus status = statusMap.get(adapterClass);
                assert status != null;
            }
            AdView adView = new AdView(this);
            adView.setAdUnitId(getString(R.string.banner_id));
            ((FrameLayout)findViewById(R.id.adView)).addView(adView);
            AdRequest adRequest = new AdRequest.Builder().build();
            adView.setAdSize(getAdSize(this));
            adView.loadAd(adRequest);
        });
        exitSheet = new ExitSheet(this);
        mAppUpdateManager = AppUpdateManagerFactory.create(this);
        drawerLayout = findViewById(R.id.drawer_layout);
        ViewPager2 viewPager = findViewById(R.id.viewPager);
        TabLayout tabLayout = findViewById(R.id.tabLayout);
        findViewById(R.id.ivMenu).setOnClickListener(view -> {
            if(drawerLayout.isDrawerOpen(GravityCompat.START)) {
                drawerLayout.closeDrawer(GravityCompat.START);
            } else {
                drawerLayout.openDrawer(GravityCompat.START);
            }
        });
        viewPager.setAdapter(new ViewPagerAdapter(this));
        new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> tab.setText(categoryList.get(position).getName())).attach();
        NavigationView navigationView = findViewById(R.id.navigation);
        navigationView.setNavigationItemSelectedListener(item -> {
            drawerLayout.closeDrawer(GravityCompat.START);
            if(item.getItemId() == R.id.share) {
                startActivity(Intent.createChooser(new Intent(Intent.ACTION_SEND).setType("text/plain")
                        .putExtra(Intent.EXTRA_SUBJECT,getString(R.string.app_name))
                        .putExtra(Intent.EXTRA_TEXT,SHARE_TEXT + getPackageName()),"Share"));
            } else if(item.getItemId() == R.id.contact) {
                alertBox(MainActivity.this,CONTACT_US_TEXT);
            } else if(item.getItemId() == R.id.policy) {
                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(POLICY_LINK)));
            }
            return false;
        });
        findViewById(R.id.fav).setOnClickListener(view -> startActivity(new Intent(this,FavoriteActivity.class)));
    }

    @Override
    public void onStart() {
        super.onStart();
        checkUpdate();
    }

    private void checkUpdate() {
        Task<AppUpdateInfo> appUpdateInfoTask = mAppUpdateManager.getAppUpdateInfo();
        appUpdateInfoTask.addOnSuccessListener(appUpdateInfo -> {
            if (appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE && appUpdateInfo.isUpdateTypeAllowed(AppUpdateType.IMMEDIATE)) {
                startUpdateFlow(appUpdateInfo);
            } else if  (appUpdateInfo.updateAvailability() == UpdateAvailability.DEVELOPER_TRIGGERED_UPDATE_IN_PROGRESS){
                startUpdateFlow(appUpdateInfo);
            }
        });
    }

    private void startUpdateFlow(AppUpdateInfo appUpdateInfo) {
        try {
            mAppUpdateManager.startUpdateFlowForResult(appUpdateInfo,AppUpdateType.IMMEDIATE,this,RC_APP_UPDATE);
        } catch (IntentSender.SendIntentException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RC_APP_UPDATE) {
            if (resultCode == RESULT_CANCELED) {
                makeText(this,"Update canceled by user!",LENGTH_SHORT).show();
            } else if (resultCode == RESULT_OK) {
                makeText(this,"Update success!",LENGTH_SHORT).show();
            } else {
                makeText(this,"Update Failed!",LENGTH_SHORT).show();
                checkUpdate();
            }
        }
    }

    @Override
    public void onBackPressed() {
        if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
            drawerLayout.closeDrawer(GravityCompat.START);
        } else {
            exitSheet.show(getSupportFragmentManager(),SHEETS);
        }
    }
}