package com.team.app.activities;

import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.team.app.Constant;
import com.team.app.Functions;
import com.team.app.LiveScore;
import com.team.app.R;
import com.team.app.SliderView;
import com.team.app.controllers.HomePagerController;
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.tabs.TabLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class Home_Activity extends AppCompatActivity {

    private ViewPager viewPager;
    private AdView adView0;
    private DrawerLayout drawerLayout;
    private SliderView sliderView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        sliderView = findViewById(R.id.sliderView);
        MobileAds.initialize(this, initializationStatus -> {
            Map<String, AdapterStatus> statusMap = initializationStatus.getAdapterStatusMap();
            for (String adapterClass : statusMap.keySet()) {
                AdapterStatus status = statusMap.get(adapterClass);
            }
            FrameLayout adContainerView0 = findViewById(R.id.bannerAdView);
            if(Constant.adShown && !Constant.BANNER_ADS_ID.equals("")) {
                adView0 = new AdView(this);
                adView0.setAdUnitId(Constant.BANNER_ADS_ID);
                adContainerView0.addView(adView0);
                adView0.setAdSize(Functions.getAdSize(this));
                adView0.loadAd(new AdRequest.Builder().build());
                adContainerView0.setVisibility(View.VISIBLE);
            }
        });
        View view = findViewById(R.id.live);
        LiveScore liveScore = new LiveScore(this,view);
        liveScore.getScore(); startSlideShow();
        drawerLayout = findViewById(R.id.drawerLayout);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ActionBarDrawerToggle abdt = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.app_name, R.string.app_name);
        drawerLayout.addDrawerListener(abdt); abdt.syncState();
        drawerSetup(); tabLayoutSetup();
    }

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

    private void tabLayoutSetup() {
        TabLayout tabLayout = findViewById(R.id.tabLayout);
        viewPager = findViewById(R.id.viewPager);
        HomePagerController homePagerController = new HomePagerController(getSupportFragmentManager(),FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT, tabLayout.getTabCount());
        this.viewPager.setAdapter(homePagerController);
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

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

            }
        });
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    }

    private void drawerSetup() {
        TextView tips = findViewById(R.id.nav_tips);
        tips.setOnClickListener(v -> {
            drawerLayout.closeDrawer(GravityCompat.START);
            startActivity(new Intent(Home_Activity.this,
                    TipsActivity.class));
        });
        TextView faq = findViewById(R.id.nav_faq);
        faq.setOnClickListener(v -> {
            drawerLayout.closeDrawer(GravityCompat.START);
            startActivity(new Intent(Home_Activity.this,
                    FAQActivity.class));
        });
        TextView contact = findViewById(R.id.nav_contact_us);
        contact.setOnClickListener(v -> {
            drawerLayout.closeDrawer(GravityCompat.START);
            sendEmail();
        });
        TextView share = findViewById(R.id.nav_share);
        share.setOnClickListener(v -> {
            drawerLayout.closeDrawer(GravityCompat.START);
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("text/plain");
            intent.putExtra(Intent.EXTRA_TEXT, getResources().getString(R.string.app_share_text) + " https://play.google.com/store/apps/details?id=" + getPackageName());
            startActivity(intent);
        });
        TextView rate = findViewById(R.id.nav_rate);
        rate.setOnClickListener(v -> {
            drawerLayout.closeDrawer(GravityCompat.START);
            startActivity(new Intent(Intent.ACTION_VIEW,
                    Uri.parse("market://details?id=" + getPackageName())));
        });
        TextView app = findViewById(R.id.nav_apps);
        app.setOnClickListener(v -> {
            drawerLayout.closeDrawer(GravityCompat.START);
            startActivity(new Intent(Home_Activity.this,
                    AppActivity.class));
        });

    }

    public void sendEmail() {
        Intent putExtra = new Intent(Intent.ACTION_SENDTO)
                .setData(new Uri.Builder().scheme("mailto").build())
                .putExtra(Intent.EXTRA_EMAIL,new String[]{"My Dream Team Admin <help.mydreamteam@gmail.com>"})
                .putExtra(Intent.EXTRA_SUBJECT,"Hello")
                .putExtra(Intent.EXTRA_TEXT, "I need some help regarding");
        ComponentName resolveActivity = putExtra.resolveActivity(getPackageManager());
        ComponentName unflattenFromString = ComponentName.unflattenFromString("com.android.fallback/.Fallback");
        if (resolveActivity != null && !resolveActivity.equals(unflattenFromString)) {
            try {
                startActivity(Intent.createChooser(putExtra, "Send email with"));
                return;
            } catch (ActivityNotFoundException unused) {
                unused.fillInStackTrace();
            }
        }
        Toast.makeText(this,"Couldn't find an email app and account",Toast.LENGTH_SHORT).show();
    }

    private void startSlideShow() {
        String JSON_URL = Constant.APP_URL_MAIN + "api.php?slider=true";
        JsonArrayRequest request = new JsonArrayRequest(JSON_URL, response -> {
            ArrayList<String> Urls = new ArrayList<>();
            ArrayList<String> Links = new ArrayList<>();
            for (int i = 0; i < response.length(); i++) {
                try {
                    JSONObject menuItemObject = response.getJSONObject(i);
                    String thumb = menuItemObject.getString("thumb");
                    String detail = menuItemObject.getString("detail");
                    Urls.add(Constant.APP_URL_MAIN + "images/" + thumb);
                    Links.add(detail);
                } catch (JSONException exception) {
                    exception.fillInStackTrace();
                }
            }
            sliderView.setLinkImages(Urls,Links);
            TimerTask task = sliderView.getTimerTask();
            Timer timer = new Timer();
            timer.schedule(task,Urls.size() * 1000,3000);
        }, Throwable::printStackTrace);
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(request);
    }

    @Override
    public void onBackPressed() {
        finish();
    }

}
