package com.huawei.hwmdemo.view.sdk;


import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;

import androidx.annotation.NonNull;

import com.huawei.cloudlink.openapi.HWMSdk;
import com.huawei.hwmdemo.R;
import com.huawei.hwmdemo.constant.ConfigConstant;
import com.huawei.hwmdemo.dependency.NeedCustomType;
import com.huawei.hwmdemo.utils.DemoUtil;
import com.huawei.hwmdemo.utils.PreferencesUtil;
import com.huawei.hwmdemo.view.base.BaseDialogFragment;
import com.huawei.hwmfoundation.utils.FileUtil;

import java.io.File;

public class LogPathFragment extends BaseDialogFragment {
    public final static String TAG = LogPathFragment.class.getSimpleName();

    private View rootView;

    private EditText logPathET;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        rootView = inflater.inflate(R.layout.log_path_layout, container, false);
        String lastLogPath = PreferencesUtil.getStringPreference(getActivity().getApplicationContext(), ConfigConstant.KEY_LOG_PATH, "custom-log");
        logPathET = rootView.findViewById(R.id.log_path_input);
        logPathET.setText(lastLogPath);

        Button saveBtn = rootView.findViewById(R.id.save_btn);
        saveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String newLogPath = logPathET.getText().toString();
                String logPath = FileUtil.getExternalFilesDir(getContext()) + File.separator + newLogPath + File.separator;
                if (TextUtils.equals(newLogPath.trim(), lastLogPath)) {
                    DemoUtil.showToast("日志路径未发生改变：" + lastLogPath);
                    return;
                }
                HWMSdk.updateLogPath(logPath);
                PreferencesUtil.setStringPreferences(getActivity().getApplicationContext(), ConfigConstant.KEY_LOG_PATH, newLogPath);
                DemoUtil.setCustom(NeedCustomType.LOGGER_PATH, true);
                dismiss();
                showLoading();
                new Handler(Looper.getMainLooper()).postDelayed(() -> {
                    dismissLoading();
                    DemoUtil.restartApplication();
                }, 1500L);
            }
        });

        return rootView;
    }


}
