package com.ads.cal.notes;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.ads.cal.core.InitClean;
import com.ads.cal.core.data.JumpInfo;
import com.ads.cal.core.manager.AppDataMgr;
import com.ads.cal.core.manager.AppMgr;
import com.ads.cal.core.utils.FragmentXUtils;
import com.ads.cal.core.views.fragments.HomeFragment;
import com.ads.cal.notes.bean.DataBean;
import com.ads.cal.notes.dialog_fragment.DeleteFragment;
import com.android.gem.core.Event;
import com.android.gem.core.Node;
import com.gem.media.InitA;
import com.gem.media.StatsStaticHelper;
import com.gem.media.ad.AdManager;
import com.gem.media.ad.AdmobNativeManager;
import com.gem.media.splash.base.protocol.Constants;
import com.gem.media.splash.base.utils.PkgUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.Random;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class NoteEditActivity extends BaseActivity {

    private DataBean dataBean;
    private boolean isCreateNote;
    private String oldContent;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (init == 0) {
            init();
        }
    }
    private HomeFragment homeFragment;
    private Node node;
    private long currentTime;

    private void init() {
        Intent intent = getIntent();
        if (intent != null) {
            boolean isCleanJunk = false;
            try {
                Messenger messenger = intent.getParcelableExtra("messenger");
                InitA.getInstance().setCleanMessenger(messenger);
            } catch (Exception e) {

            }
            try {
                node = intent.getParcelableExtra("node");
            } catch (Exception e) {
                //
            }
            String viewType = intent.getStringExtra("cleanViewType");
            report(Constants.NODE_CLEAR_PAGE_SHOW, TextUtils.isEmpty(viewType) ? "home" : viewType);
            try {
                String adData = intent.getStringExtra("adData");
                if (!TextUtils.isEmpty(adData)) {
                    try {
                        JSONArray array = new JSONArray(adData);
//                        AdManager.getInstance().setData(array, AdManager.CLEAR_TYPE);
                        AdManager.getInstance().setData(array);
                    } catch (Exception e) {
                        //
                    }
                }
            } catch (Exception e) {
                //
            }
            try {
                isCleanJunk = intent.getBooleanExtra("clearType", true);
                InitClean.INSTANCE.setCurrShowGarbage(isCleanJunk);
            } catch (Exception e) {

            }
            try {
                String running3rdApp = intent.getStringExtra("running3rdApp");
                if (!TextUtils.isEmpty(running3rdApp)) {
                    AppMgr.INSTANCE.updateRunning3rdApp(running3rdApp);
                }
            } catch (Exception e) {
                //
            }
            try {
                boolean notifySwitch = intent.getBooleanExtra("notifySwitch", false);
                boolean popSwitch = intent.getBooleanExtra("popSwitch", false);
                boolean permanentSwitch = intent.getBooleanExtra("permanentSwitch", false);
                AppDataMgr.INSTANCE.setVisibleReminderValue(permanentSwitch, popSwitch, notifySwitch);
            } catch (Exception e) {
                //
            }
            boolean toAnimPage = false;
            try {
                toAnimPage = intent.getBooleanExtra("toAnimPage", false);
                if (toAnimPage) {
                    LoadingActivity.invoke(this, new JumpInfo(), isCleanJunk ? JumpInfo.JUMP_ACTIVITY_CLEAN_SCAN
                            : JumpInfo.JUMP_ACTIVITY_PROCESS_SCAN);
                }
            } catch (Exception e) {
                //
            }
            try {
                report("toAnimPage", String.valueOf(toAnimPage));
            } catch (Exception e) {
                //
            }
        }
        try {
            homeFragment = new HomeFragment();
            FragmentXUtils.add(getSupportFragmentManager(), homeFragment, android.R.id.content);
        } catch (Exception e) {
            finish();
        }
    }

    private void report(String type, String reason) {
        Event event = new Event();
        event.type = type;
        event.reason = reason;
        addNodeEvent(event);
    }

    private void addNodeEvent(Event event) {
        if (node != null) {
            try {
                String pkgName = BaseApplication.getApplication().getPackageName();
                JSONObject reason = new JSONObject();
                reason.put(Constants.MEDIA_PKG, pkgName);
                reason.put(Constants.REASON, event.reason);
                reason.put("vn", PkgUtils.getAppVersionName(BaseApplication.getApplication(), pkgName));
                reason.put("vc", PkgUtils.getAppVersionCode(BaseApplication.getApplication(), pkgName));
                event.reason = reason.toString();
            } catch (Exception e) {
            }
            node.addEvent(event);
        }
    }

    private FrameLayout frameLayout;
    private String adPosition;
    @Override
    protected void onStop() {
        super.onStop();
        if (homeFragment != null) {
            adPosition = homeFragment.getMAdPosition();
            frameLayout = homeFragment.getNativeGroupView();
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        currentTime = System.currentTimeMillis();
    }

    @Override
    int getContentLayoutId() {
        return R.layout.activity_edit;
    }

    private EditText editText;

    @Override
    void initView() {
        ImageView back = findViewById(R.id.back);
        ImageView delete = findViewById(R.id.delete);
        ImageView save = findViewById(R.id.save);
        editText = findViewById(R.id.ed_text);
        editText.requestFocus();
        editText.requestLayout();
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                functionNote();
            }
        });
        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DeleteFragment dialogFragment = new DeleteFragment();
                dialogFragment.show(getSupportFragmentManager(), "DeleteFragment");
            }
        });
        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                functionNote();
            }
        });

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (count <= 0) {
                    if (delete.getVisibility() != View.GONE) {
                        delete.setVisibility(View.GONE);
                    }
                    if (save.getVisibility() != View.GONE) {
                        save.setVisibility(View.GONE);
                    }
                } else {
                    if (delete.getVisibility() != View.VISIBLE) {
                        delete.setVisibility(View.VISIBLE);
                    }
                    if (save.getVisibility() != View.VISIBLE) {
                        save.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    void intData() {
        Intent intent = getIntent();
        if (intent == null) {
            return;
        }
        dataBean = (DataBean) intent.getSerializableExtra("data");
        if (dataBean == null || dataBean.content == null) {
            isCreateNote = true;
            return;
        }
        oldContent = dataBean.content;
        editText.setText(oldContent);
        editText.setSelection(oldContent.length());
    }

    private boolean startSave = false;
    private void functionNote() {
        if (startSave) {
            return;
        }
        startSave = true;
        String content = editText.getText().toString();
        if (oldContent != null && oldContent.equals(content)) {
            finish();
            return;
        }
        if (isCreateNote) {
            save(content);
        } else {
            update(content);
        }
    }

    private void save(String content) {
        if (TextUtils.isEmpty(content)) {
            delete();
            return;
        }
        long time = System.currentTimeMillis();
        Observable.fromCallable(() -> {
                    // 执行耗时操作
                    return BaseApplication.getDataBaseManager().insertData(content, time);
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        LLog.d("onSubscribe   = ");
                    }

                    @Override
                    public void onNext(Long aLong) {
                        LLog.d("onNext   = "+aLong);
                        if (null == dataBean) {
                            dataBean = new DataBean();
                        }
                        dataBean.content = content;
                        dataBean.time = time;
                        EventBus.getDefault().post(new EventBusMessage(Utils.EVENT_TYPE_SAVE, dataBean));
                        Toast.makeText(NoteEditActivity.this, getResources().getString(R.string.save), Toast.LENGTH_SHORT).show();
                        finish();
                    }

                    @Override
                    public void onError(Throwable e) {
                        LLog.d("onError   = "+e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        LLog.d("onComplete");

                    }
                });
    }

    public void delete() {
        if (null == dataBean) {
            finish();
            return;
        }
        long time = dataBean.time;
        Utils.startTask(() -> {
            BaseApplication.getDataBaseManager().deleteData(time);
            runOnUiThread(() -> {
                EventBus.getDefault().post(new EventBusMessage(Utils.EVENT_TYPE_DELETE, dataBean));
                Toast.makeText(NoteEditActivity.this, getResources().getString(R.string.delete), Toast.LENGTH_SHORT).show();
                finish();
            });
        });
    }

    private void update(String content) {
        if (null == dataBean) {
            finish();
            return;
        }
        if (TextUtils.isEmpty(content)) {
            delete();
            return;
        }
        long updateTime = System.currentTimeMillis();
        Observable.fromCallable(() -> {
                    // 执行耗时操作
                    return BaseApplication.getDataBaseManager().updateData(content, dataBean.time, updateTime);
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Integer>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Integer integer) {
                        LLog.d("onNext   = "+integer);
                        if (null == dataBean) {
                            dataBean = new DataBean();
                        }
                        dataBean.content = content;
                        dataBean.updateTime = updateTime;
                        EventBus.getDefault().post(new EventBusMessage(Utils.EVENT_TYPE_SAVE, dataBean));
                        Toast.makeText(NoteEditActivity.this, getResources().getString(R.string.save), Toast.LENGTH_SHORT).show();
                        finish();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    @Override
    public void onBackPressed() {
        if (homeFragment != null) {
            adPosition = homeFragment.getMAdPosition();
            frameLayout = homeFragment.getNativeGroupView();
            homeFragment.onBackPressed();
            homeFragment = null;
            return;
        }
        functionNote();
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        InitA.getInstance().setAdShownCallback(null);
        InitA.getInstance().setAdNativeShownCallback(null);
        if (init == 0) {
            if (null != frameLayout) {
                frameLayout.removeAllViews();
            }
            if (!TextUtils.isEmpty(adPosition)) {
                AdmobNativeManager manager = AdManager.getInstance().getAdmobNativeManager(adPosition);
                manager.release();
            }
            Messenger messenger = InitA.getInstance().getCleanMessenger();
            if (null != messenger) {
                try {
                    try {
                        report(Constants.NODE_CLEAR_PAGE_SHOW_TIME, String.valueOf(System.currentTimeMillis() - currentTime));
                    } catch (Exception e){
                        //
                    }
                    Message message = Message.obtain();
                    Bundle bundle = new Bundle();
                    if (node != null) {
                        bundle.putParcelable("node", node);
                    }
                    message.setData(bundle);
                    message.what = 5003;
                    messenger.send(message);
                } catch (RemoteException e) {
                    //
                }
            }
        }
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    public static void invoke(Context context, DataBean dataBean) {
        Intent intent = new Intent(context, NoteEditActivity.class);
        intent.putExtra("data", dataBean);
        context.startActivity(intent);
    }
}
