package com.ttstd.dialer.fragment.home;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
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 androidx.fragment.app.Fragment;

import com.hjq.toast.Toaster;
import com.ttstd.dialer.R;
import com.ttstd.dialer.activity.contact.list.ContactListActivity;
import com.ttstd.dialer.activity.weather.main.WeatherMainActivity;
import com.ttstd.dialer.base.mvvm.fragment.BaseMvvmFragment;
import com.ttstd.dialer.databinding.FragmentHomeBinding;
import com.ttstd.dialer.utils.ApkUtils;
import com.ttstd.dialer.utils.DateUtil;
import com.ttstd.dialer.utils.LunarCalendarFestivalUtils;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link HomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomeFragment extends BaseMvvmFragment<HomeViewModel, FragmentHomeBinding> {
    private static final String TAG = "HomeFragment";

    private Activity mContext;
    private LunarCalendarFestivalUtils mFestivalUtils;

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public HomeFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment HomeFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static HomeFragment newInstance(String param1, String param2) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initDataBinding() {
        mContext = getActivity();
        mViewModel.setContext(mContext);
        mViewModel.setVDBinding(mViewDataBinding);
        mViewModel.setLifecycle(getLifecycleSubject());
        mViewDataBinding.setClick(new BtnClick());
    }

    @Override
    protected void initView(Bundle bundle) {
        mFestivalUtils = new LunarCalendarFestivalUtils();
        setTime();
    }

    @Override
    protected void initData(Bundle savedInstanceState) {

    }

    @Override
    public void fetchData() {

    }

    @Override
    public void onStart() {
        super.onStart();
        Log.e(TAG, "onStart: ");
        registerReceivers();
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.e(TAG, "onStop: ");
        unregisterReceivers();
    }

    public void registerReceivers() {
        registerTimeReceiver();
    }

    private void unregisterReceivers() {
        if (null != mTimeReceiver) {
            mContext.unregisterReceiver(mTimeReceiver);
        }

    }


    /**
     * 时间
     */
    private void registerTimeReceiver() {
        if (null == mTimeReceiver) {
            mTimeReceiver = new TimeReceiver();
        }
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_DATE_CHANGED);
        filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
        filter.addAction(Intent.ACTION_TIME_CHANGED);
        filter.addAction(Intent.ACTION_TIME_TICK);
        mContext.registerReceiver(mTimeReceiver, filter);
    }

    private TimeReceiver mTimeReceiver;

    private class TimeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.e("TimeReceiver", "onReceive: " + action);
            switch (action) {
                case Intent.ACTION_DATE_CHANGED:
                case Intent.ACTION_TIMEZONE_CHANGED:
                case Intent.ACTION_TIME_CHANGED:
                case Intent.ACTION_TIME_TICK:
                    setTime();
                    break;
                default:
            }
        }
    }

    private void setTime() {
        if (isAdded()) {
            mViewDataBinding.tvTime.setText(DateUtil.formatDateHour());
            mViewDataBinding.tvDate.setText(DateUtil.formatDateDay());
            mViewDataBinding.tvWeek.setText(DateUtil.convertToChineseWeekdayAll());
            mViewDataBinding.tvLunar.setText(mFestivalUtils.getLunarCalendar());
        }
    }


    public class BtnClick {
        public void openContact(View view) {
            startActivity(new Intent(mContext, ContactListActivity.class));
        }

        public void openSettings(View view) {
            Intent intent = new Intent(Settings.ACTION_SETTINGS);
            try {
                startActivity(intent);
            } catch (Exception e) {
                Log.e(TAG, "openSettings: " + e.getMessage());
            }
        }

        public void openDouyin(View view) {
            if (ApkUtils.isInstalled(mContext, "com.ss.android.ugc.aweme")) {
                ApkUtils.openPackage(mContext, "com.ss.android.ugc.aweme");
            } else {
                Toaster.show("抖音未安装，请安装后使用");
                ApkUtils.openAppStore(mContext, "com.ss.android.ugc.aweme");
            }
        }

        public void openWeixin(View view) {
            if (ApkUtils.isInstalled(mContext, "com.tencent.mm")) {
                Intent intent = new Intent();
                ComponentName cmp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI");
                intent.setAction(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_LAUNCHER);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                intent.setComponent(cmp);
                try {
                    startActivity(intent);
                } catch (Exception e) {
                    Log.e(TAG, "launchWeChat: " + e.getMessage());
                    Toaster.show("打开微信失败");
                    ApkUtils.openAppStore(mContext, "com.tencent.mm");
                }
            } else {
                Toaster.show("微信未安装，请安装后使用");
                ApkUtils.openAppStore(mContext, "com.tencent.mm");
            }
        }

        public void openWeather(View view) {
            startActivity(new Intent(mContext, WeatherMainActivity.class));
        }

    }

}
