package com.key.coolkeyboard.fragment;


import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;

import androidx.core.view.GravityCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.key.coolkeyboard.CoolKeyboardSkin;
import com.key.coolkeyboard.R;
import com.key.coolkeyboard.activity.AllActivity;
import com.key.coolkeyboard.activity.MainActivity;
import com.key.coolkeyboard.activity.PreviewActivity;
import com.key.coolkeyboard.activity.SerachActivity;
import com.key.coolkeyboard.activity.SettingActivity;
import com.key.coolkeyboard.activity.WebActivity;
import com.key.coolkeyboard.adapter.ThumAdapter;
import com.key.coolkeyboard.data.Otherdata;
import com.key.coolkeyboard.databinding.FragmentMainBinding;
import com.key.coolkeyboard.tool.Mytool;
import com.key.coolkeyboard.tool.SpaceItem;
import com.key.coolkeyboard.tool.StaticValue;
import com.key.coolkeyboard.topon.AdManager;
import com.key.coolkeyboard.topon.onActionListener;
import com.youth.banner.adapter.BannerImageAdapter;
import com.youth.banner.holder.BannerImageHolder;
import com.youth.banner.indicator.CircleIndicator;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.transformer.DepthPageTransformer;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class MainFragment extends Fragment {
    FragmentMainBinding binding;
    private List<Otherdata> bannerrandomlist = new ArrayList<>();
    private List<Otherdata> mainrandomlist = new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentMainBinding.inflate(inflater, container, false);

//        binding.mainEdit.clearFocus();
//        binding.mainEdit.setFocusable(false);
//        binding.mainEdit.setFocusableInTouchMode(false);


        initData();
        initEvent();


        return binding.getRoot();
    }

    private void initEvent() {

        binding.mainSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.mainDrawerLayout.openDrawer(GravityCompat.START);
            }
        });

        binding.rateCons.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    String url = "https://play.google.com/store/apps/details?id=com.key.coolkeyboard";
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    startActivity(intent);
                } catch (Exception e) {

                }

            }
        });

        binding.shareCons.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent share = new Intent(Intent.ACTION_SEND);
                share.setType("text/plain");
                share.putExtra(Intent.EXTRA_SUBJECT, R.string.app_name);
                String text = getString(R.string.share_title);
                text = text + "\n https://play.google.com/store/apps/details?id=" + "com.key.coolkeyboard";
                share.putExtra(Intent.EXTRA_TEXT, text);
                startActivity(Intent.createChooser(share, "choose one"));
            }
        });

        binding.privacyCons.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(requireContext(), WebActivity.class);
                startActivity(intent);
            }
        });

        binding.minSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String text = binding.mainEdit.getText().toString();
                hideKeyboard();
                if (!TextUtils.isEmpty(text)) {
                    Intent intent = new Intent(requireContext(), SerachActivity.class);
                    intent.putExtra(StaticValue.KEY_TEXT, text);
                    intent.putExtra(StaticValue.KEY_ISMAINSH, text);
                    startActivity(intent);
                } else {
                    Toast.makeText(requireContext(), getString(R.string.text_tips), Toast.LENGTH_SHORT).show();
                }
            }
        });

        binding.mainViewAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AdManager.showTopOn(requireActivity(), new onActionListener() {
                    @Override
                    public void onAction() {
                        Intent intent = new Intent(requireContext(), AllActivity.class);
                        startActivity(intent);
                    }
                });

            }
        });

    }

    private void initData() {
        binding.mainTitle.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "Baumans-Regular.ttf"));
        binding.settingTitle.setTypeface(Typeface.createFromAsset(getContext().getAssets(), "Baumans-Regular.ttf"));

        initBanner();
        initMainrv();

    }

    private void initMainrv() {

        List<Otherdata> mainrvdataList = generateRandomOtherdata(0, 20);
        for (Otherdata data : mainrvdataList) {
            if (mainrandomlist.size() < 20) {
                mainrandomlist.add(data);
            }
        }
        binding.mainRv.setAdapter(new ThumAdapter(requireContext(), mainrandomlist));
        binding.mainRv.setLayoutManager(new GridLayoutManager(requireContext(), 2));
        SpaceItem spaceItem = new SpaceItem(16, 16, 16);
        binding.mainRv.addItemDecoration(spaceItem);
    }

    private void initBanner() {

        List<Otherdata> bannerdataList = generateRandomOtherdata(0, 5);
        for (Otherdata data : bannerdataList) {
            if (bannerrandomlist.size() < 5) {
                bannerrandomlist.add(data);
            }
        }

        binding.mainBanner.setAdapter(new BannerImageAdapter<Otherdata>(bannerrandomlist) {
            @Override
            public void onBindView(BannerImageHolder holder, Otherdata data, int position, int size) {
                ImageView imageView = holder.imageView;
                Glide.with(requireContext())
                        .load(data.getPreview())
                        .placeholder(R.color.pre_load_color)
                        .into(imageView);
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            }
        });

        binding.mainBanner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(Object data, int position) {
                Otherdata otherdata = bannerrandomlist.get(position);
                String url = otherdata.getZipUrl();
                String pre = otherdata.getPreview();
                String name = otherdata.getTitle();
                Intent intent = new Intent(requireContext(), PreviewActivity.class);
                intent.putExtra(StaticValue.KEY_PRE, pre);
                intent.putExtra(StaticValue.KEY_URL, url);
                intent.putExtra(StaticValue.KEY_NAME, name);
                requireContext().startActivity(intent);
            }
        });
        binding.mainBanner.setIndicator(new CircleIndicator(requireContext()));
        binding.mainBanner.setBannerRound(10);
        binding.mainBanner.setIndicatorRadius(100);
        binding.mainBanner.setPageTransformer(new DepthPageTransformer());
    }

    private static List<Otherdata> generateRandomOtherdata(int star, int end) {
        List<Otherdata> allOtherdata = CoolKeyboardSkin.getAlldataList();
        Collections.shuffle(allOtherdata);
        return allOtherdata.subList(star, end);
    }

    private void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) requireContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(binding.mainEdit.getWindowToken(), 0);
        binding.mainEdit.clearFocus();
    }

    @Override
    public void onResume() {
        super.onResume();
        hideKeyboard();
    }

    @Override
    public void onPause() {
        super.onPause();
        hideKeyboard();
    }
}