package com.colorful.keyboard.theme;

import static com.colorful.keyboard.theme.net.BaseInitApiRequest.getNetData;
import static com.colorful.keyboard.theme.net.BaseInitApiRequest.initHHYApiStores;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.colorful.keyboard.theme.constant.ConfigConstant;
import com.colorful.keyboard.theme.latin.LatinIME;
import com.colorful.keyboard.theme.model.ThemeDetailsBean;
import com.colorful.keyboard.theme.myutil.ConfigFileUtils;
import com.colorful.keyboard.theme.myutil.ImmUtils;
import com.colorful.keyboard.theme.myutil.SPUtils;
import com.colorful.keyboard.theme.net.ApiCallbackCommon;

import java.io.File;
import java.util.HashMap;

public class ThemeSettingsActivity  extends AppCompatActivity {

    private String key;
    private String title;
    private TextView tvStepOne;
    private TextView tvStepTwo;
    private LinearLayout ll_setting;
    private LinearLayout ll_step;
    private TextView tv_to_setting;
    ThemeDetailsBean themeDetailsBean;
    boolean isCurrentSetting  = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_setting_theme);
        ImmUtils.setStatusBar(this,false,false);
        title = getIntent().getStringExtra("title");
        key = getIntent().getStringExtra("key");
        String url = getIntent().getStringExtra("url");

        ImageView imageView = findViewById(R.id.iv_back_setting);
        ll_setting = findViewById(R.id.ll_setting);
        ll_step = findViewById(R.id.ll_step);
        tv_to_setting = findViewById(R.id.tv_to_setting);


        tvStepOne = findViewById(R.id.tv_step_one);
        tvStepTwo = findViewById(R.id.tv_step_two);

        ImageView iv_theme = findViewById(R.id.iv_theme);
        Glide.with(this).load(url).into(iv_theme);
        TextView tv_setting_title = findViewById(R.id.tv_setting_title);
        tv_setting_title.setText(title);

        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        getInfo();

       /* new MaxAdInputManager(this, Constant.adIdSee, new AdInputListener() {
            @Override
            public void adShow() {
            }

            @Override
            public void adClose() {
            }
        });*/


    }

    @Override
    protected void onResume() {
        super.onResume();
        if(isInputMethodOfThisImeEnabled()){
            tvStepOne.setBackground(getResources().getDrawable(R.drawable.shape_green));
        }else {
            tvStepOne.setBackground(getResources().getDrawable(R.drawable.shape_grey));
        }
        String string = Settings.Secure.getString(getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD);

        boolean isMy = string.contains("com.colorful.keyboard.theme");

        if(isMy){
            tvStepTwo.setBackground(getResources().getDrawable(R.drawable.shape_green));
        }else {
            tvStepTwo.setBackground(getResources().getDrawable(R.drawable.shape_grey));
        }
        Log.e("666",string);

        tvStepOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!isInputMethodOfThisImeEnabled()){
                    Intent intent = new Intent(android.provider.Settings.ACTION_INPUT_METHOD_SETTINGS);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }
            }
        });

        tvStepTwo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!isMy){

                    IntentFilter intentFilter = new IntentFilter();
                    intentFilter.addAction(INPUT_METHOD_ACTION);
                    registerReceiver(inputMethodChangeReceiver, intentFilter);

                    try {
                        ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).showInputMethodPicker();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        if(isMy && isInputMethodOfThisImeEnabled()){
            ll_step.setVisibility(View.GONE);
            ll_setting.setVisibility(View.VISIBLE);
        }else{
            ll_step.setVisibility(View.VISIBLE);
            ll_setting.setVisibility(View.GONE);
        }

        tv_to_setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!isCurrentSetting){
                    if (null!=themeDetailsBean){
                        SPUtils.getInstance().put("id",themeDetailsBean.getData().getItem().getKey());
                       /* new MaxAdInputManager(ThemeSettingsActivity.this, Constant.adIdSetting, new AdInputListener() {
                            @Override
                            public void adShow() {
                            }

                            @Override
                            public void adClose() {
                                saveConfigImgToLocal(ThemeSettingsActivity.this,themeDetailsBean.getData().getItem().getThemeContent().getImgBanner());
                            }
                        });*/
                    }
                }
            }
        });
    }

    public  void saveConfigImgToLocal(Context context, String url) {
        Glide.with(context)
                .downloadOnly()
                .load(url)
                .listener(new RequestListener<File>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<File> target, boolean isFirstResource) {
                        return false;
                    }


                    @Override
                    public boolean onResourceReady(File resource, Object model, Target<File> target, DataSource dataSource, boolean isFirstResource) {
                        configSaveToAlbum(context, resource.getAbsolutePath());
                        return false;
                    }
                })
                .preload();

    }

    public  void configSaveToAlbum(Context context, String srcPath) {
        String imageSrc = context.getExternalFilesDir("input").getAbsolutePath() +"image/"+ System.currentTimeMillis() + ".png";
        File file = new File(imageSrc);
        SPUtils.getInstance().put("bg",imageSrc);

        App.Companion.getApp().stopService(new Intent(App.Companion.getApp(), LatinIME.class));
        App.Companion.getApp().startService(new Intent(App.Companion.getApp(),LatinIME.class));
        ConfigConstant.isNeedSetting = true;
        Toast.makeText(ThemeSettingsActivity.this,"Success",Toast.LENGTH_SHORT).show();
        if(SPUtils.getInstance().getString("id") .equals(themeDetailsBean.getData().getItem().getKey()) ){
            isCurrentSetting = true;
            tv_to_setting.setBackground(getResources().getDrawable(R.drawable.shape_green));
        }else{
            tv_to_setting.setBackground(getResources().getDrawable(R.drawable.shape_grey));
            isCurrentSetting = false;
        }
        boolean isCopySuccess = false;
        try {
            isCopySuccess = ConfigFileUtils.configCopy(srcPath, file.getAbsolutePath(),false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        /*if (isCopySuccess) {
            try {
                MediaStore.Images.Media.insertImage(context.getContentResolver(),
                        file.getAbsolutePath(),file.getName() , null);
                context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(file.getAbsolutePath())));
                Toast.makeText(context,"successfully",Toast.LENGTH_SHORT).show();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

        } else {

        }*/
    }


    private static final String INPUT_METHOD_ACTION = "android.intent.action.INPUT_METHOD_CHANGED";

    private BroadcastReceiver inputMethodChangeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(INPUT_METHOD_ACTION)) {
                //监听到输入法发生改变
                onResume();
            }
        }
    };


    private boolean isInputMethodOfThisImeEnabled() {
        final InputMethodManager imm =
                (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        final String imePackageName = getPackageName();
        for (final InputMethodInfo imi : imm.getEnabledInputMethodList()) {
            if (imi.getPackageName().equals(imePackageName)) {
                return true;
            }
        }
        return false;
    }

    private void getInfo(){
        HashMap<String,String> hashMap = new HashMap<>();
        hashMap.put("sign","a28aadc61c76c754944f6ddb48962c9c");
        getNetData(initHHYApiStores().getDetailsTheme(key,hashMap),
                new ApiCallbackCommon<ThemeDetailsBean>(this, false) {
                    @Override
                    public void onSuccess(ThemeDetailsBean model) {
                        themeDetailsBean = model;
                        Log.e("666",SPUtils.getInstance().getString("id"));
                        Log.e("666",model.getData().getItem().getKey());
                        Log.e("666",model.getData().getItem().getKey());
                        Log.e("666",(SPUtils.getInstance().getString("id") == model.getData().getItem().getKey())+"");
                        if(SPUtils.getInstance().getString("id") .equals(model.getData().getItem().getKey()) ){
                            isCurrentSetting = true;
                            tv_to_setting.setBackground(getResources().getDrawable(R.drawable.shape_green));
                        }else{
                            tv_to_setting.setBackground(getResources().getDrawable(R.drawable.shape_grey));
                            isCurrentSetting = false;
                        }
                    }

                    @Override
                    public void onFailure(com.colorful.keyboard.theme.net.ApiException ex) {

                    }
                });
    }
}
