package com.xplora.xpsettings.Activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.xplora.xpsettings.Adapter.BaseListAdapter;
import com.xplora.xpsettings.Data.DatabaseHelper;
import com.xplora.xpsettings.Fragment.RingtoneNewFragment;
import com.xplora.xpsettings.Model.BaseModel;
import com.xplora.xpsettings.Model.RingtoneModel;
import com.xplora.xpsettings.Observer.Listener;
import com.xplora.xpsettings.Observer.RingtonesContentObserver;
import com.xplora.xpsettings.R;
import com.xplora.xpsettings.Data.DataManager;
import com.xplora.xpsettings.Utils.Constant;
import com.xplora.xpsettings.Utils.Macros;
import com.xplora.xpsettings.Utils.MetaData;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;


public class RingToneActivity extends BaseActionActivity implements Listener.ContentListener {
    private ArrayList<RingtoneModel> mRingtoneList = new ArrayList<>();
    private int selectIndex = 0;

    public RingtoneNewFragment mNewRingtoneFragment = null;
    public RelativeLayout mContentGuideLayout = null;
    public boolean mIsGuide = false;
    public Timer mTimer = null;
    public RingtonesContentObserver mRingtonesContentObserver = null;
    public int mRepeatCount = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);

        if(Macros.DEBUG)
            initDataDebug();
        else
            initData();

        initView();

        //去除launcher中new message
        DataManager.setNewMessageStatus();
    }

    private void initData() {
        mRingtoneList = DataManager.getRingToneList();
        Log.d(TAG, "initData: " + mRingtoneList.size());
        Uri defaultUri = DataManager.getDefaultRingToneUri();
        for (int i = 0; i < mRingtoneList.size(); i++) {
            RingtoneModel ringModel = mRingtoneList.get(i);
            BaseModel model = new BaseModel();
            model.title = ringModel.ringtone.getTitle(this);
            model.isOn = ringModel.uri.toString().equals(defaultUri.toString());
            model.cellType = Constant.CellType.CHECKBOX;
            model.isHighlight = false;
            mDataList.add(model);
            if (model.isOn) {
                selectIndex = i;
            }
        }
    }

    private void initDataDebug() {
        for (int i = 0; i < 10; i++) {
            BaseModel model = new BaseModel();
            model.title = "Ringtone_" + i;
            model.isOn = i == 2;
            model.cellType = Constant.CellType.CHECKBOX;
            mDataList.add(model);
            if (model.isOn) {
                selectIndex = i;
            }
        }
    }

    private void initView() {
        mContentGuideLayout = findViewById(R.id.mContentGuideLayout);
        ListView listView = findViewById(R.id.activity_listview);

        mAdapter = new BaseListAdapter(this, 0, mDataList);
        listView.setAdapter(mAdapter);
        listView.setDivider(new ColorDrawable(Color.TRANSPARENT));
        listView.setDividerHeight(0);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                onItemClickEx(position);
                cancelGuide();
            }
        });
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == 1) {
                    cancelGuide();
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });
    }

    private void onItemClickEx(int position) {
        if (Macros.DEBUG) {
            selectIndex = position;
            refresh(position);
        } else {
            playRingtone(position);
            selectIndex = position;

            saveRingtone(position);
            saveResult(position);
            refresh(position);
        }
    }

    private void refresh(int position) {
        for (int i = 0; i < mDataList.size(); i++) {
            BaseModel model = mDataList.get(i);
            model.isOn = position == i;
            model.cellType = Constant.CellType.CHECKBOX;
        }
        mAdapter.setBaseObjects(mDataList);
        mAdapter.notifyDataSetInvalidated();
    }

    @Override
    public void onContentDownloadBegin() {
        Log.d(TAG, "onRingtoneDownloadBegin: ");
        if (!Macros.DEBUG_RINGTONG_NEW) {
            DatabaseHelper.modifyRingtoneStatusDownloading(this);
        }
        onTimerCallback(10);
        mRepeatCount = 2;
    }

    @Override
    public void onContentDownloadEnd() {
        Log.d(TAG, "onRingtoneDownloadEnd: ");
        new Thread(()->{
            ArrayList<RingtoneModel> newDataList = DataManager.getRingToneList();
            if (newDataList.size() == mDataList.size()) {
                Log.d(TAG, "onRingtoneDownloadEnd:  return");
                if (mRepeatCount > 0) {
                    onTimerCallback(20);
                    mRepeatCount-=1;
                }
                return;
            }
            Log.d(TAG, "onRingtoneDownloadEnd: ok");
            for (RingtoneModel ringModel : newDataList) {
                Log.d(TAG, "onRingtoneDownloadEnd: new: " + ringModel.uri);
                boolean isFind = false;
                for (RingtoneModel model : mRingtoneList) {
                    Log.d(TAG, "onRingtoneDownloadEnd: old " + model.uri);

                    String name_new = ringModel.ringtone.getTitle(RingToneActivity.this);
                    String name_old = model.ringtone.getTitle(RingToneActivity.this);
                    Log.d(TAG, "onRingtoneDownloadEnd: name_new :" + name_new + "  name_old" + name_old);
                    if (name_new.equals(name_old)) {
                        isFind = true;
                        break;
                    }
                }
                if (!isFind) {
                    Log.d(TAG, "onRingtoneDownloadEnd: find 1");
                    BaseModel model = new BaseModel();
                    model.title = ringModel.ringtone.getTitle(RingToneActivity.this);
                    model.isOn = false;
                    model.cellType = Constant.CellType.CHECKBOX_HIGHLIGHT;
                    model.isHighlight = true;
                    mDataList.add(0, model);
                    mRingtoneList.add(0, ringModel);
                    selectIndex ++;
                }
            }
            RingToneActivity.this.runOnUiThread(()->{
                mAdapter.setBaseObjects(mDataList);
                mAdapter.notifyDataSetInvalidated();
                if (mNewRingtoneFragment != null) {
                    mNewRingtoneFragment.changeViewViewStatus(4, 0);
                }
                onTimerCallback(1);
            });
        }).start();
    }

    @Override
    public void onContentSetup() {
        Log.d(TAG, "onRingtoneSetup: ");
        mNewRingtoneFragment = null;
        onItemClickEx(0);

        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
    }

    @Override
    public void onContentDownloadCancel(boolean isComplete) {
        mNewRingtoneFragment = null;
    }

    @Override
    public void testRingtoneDBComplete() {
        onContentDownloadEnd();
    }

    @Override
    public void onGotoWiFi() {
        mNewRingtoneFragment = null;
        Intent intent = new Intent(this, WiFiActivity.class);
        startActivityForResult(intent, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //检查是否有新铃声需要下载
        checkNewRingtone();
    }

    private void checkNewRingtone() {
        Log.d(TAG, "checkNewRingtone: ");
        boolean isFailedRingtone = false;
        boolean isAgreeRingtone = false;
        boolean isDownloadingRingtone = false;
        ArrayList<String> nameArray = new ArrayList<>();
        ArrayList<RingtoneModel> dbList = DatabaseHelper.queryRingtoneNew(this);
        for (RingtoneModel model : dbList) {
            Log.d(TAG, "checkNewRingtone: " + model.status);
            if (model.status.equals("3")) {
                isFailedRingtone = true;
                nameArray.add(model.title);
            } else if (model.status.equals("5")) {
                isAgreeRingtone = true;
                nameArray.add(model.title);
            } else if (model.status.equals("2")) {
                isDownloadingRingtone = true;
                nameArray.add(model.title);
            }
        }
        if (isFailedRingtone || isAgreeRingtone || isDownloadingRingtone) {
            String ringNames = "";
            for (int i = 0; i < nameArray.size(); i++) {
                if (i < 2) {
                    ringNames += nameArray.get(i) + ", ";
                } else {
                    ringNames += "" + (nameArray.size()-2) + " " + getString(R.string.content_more);
                    break;
                }
            }
            if (mNewRingtoneFragment == null) {
                mNewRingtoneFragment = RingtoneNewFragment.newInstance(this);
                mNewRingtoneFragment.setInitViewStatus(isFailedRingtone ? 0 : 2);
                mNewRingtoneFragment.setItemInfo(ringNames);
                mNewRingtoneFragment.show(this.getFragmentManager(), Constant.PACKAGE_NAME);
            }
        }
    }

    //检查是否下载完成或失败
    private void checkDownloadingStatus() {
        Log.d(TAG, "checkDownloadingStatus: ");
        if (mNewRingtoneFragment == null)
            return;
        Log.d(TAG, "checkDownloadingStatus: ok");
        boolean isDownloadFailed = false;
        int reason = 0;
        boolean isDownloadComplete = true;
        ArrayList<RingtoneModel> dbList = DatabaseHelper.queryRingtoneNew( RingToneActivity.this);
        for (RingtoneModel model : dbList) {
            Log.d(TAG, "checkDownloadingStatus: " + model.status);
            /*0：未下载  1：需要下载  2：下载中  3：下载失败 4：下载完成 */
            if (model.status.equals("3")) {
                isDownloadFailed = true;
                reason = model.reason != null ? Integer.parseInt(model.reason) : 0;
                break;
            } else if (!model.status.equals("4")) {
                isDownloadComplete = false;
            }
        }

        if (mNewRingtoneFragment != null) {
            if (isDownloadFailed) {
                mNewRingtoneFragment.changeViewViewStatus(3, reason);
            } else if (isDownloadComplete) {
                onContentDownloadEnd();
            }
        }
    }

    private void onTimerCallback(int type) {
        Log.d(TAG, "onTimerCallback: ");
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        mTimer = new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                RingToneActivity.this.runOnUiThread(()->{
                    Log.d(TAG, "onTimerCallback callback: " + type);
                    if (type == 1) {
                        if (mNewRingtoneFragment != null) {
                            mNewRingtoneFragment.dismissAllowingStateLoss();
                            mNewRingtoneFragment = null;
                        }
                        mIsGuide = true;
                        if (mIsGuide) {
                            mContentGuideLayout.setVisibility(View.VISIBLE);
                            onTimerCallback(3);
                        }
                    } else if (type == 2) {
                        if (mIsGuide) {
                            mContentGuideLayout.setVisibility(View.VISIBLE);
                            onTimerCallback(3);
                        }
                    } else if (type == 3) {
                        if (mIsGuide) {
                            mIsGuide = false;
                            mContentGuideLayout.setVisibility(View.GONE);
                            refresh(selectIndex);
                        }
                    } else if (type == 10) {
                        if (mNewRingtoneFragment != null) {
                            mNewRingtoneFragment.changeViewViewStatus(3, 0);
                        }
                    } else if (type == 20) {
                        onContentDownloadEnd();
                    }
                });
            }
        }, type == 10 ? 30*1000 : (type == 20 ? 2*1000 : 3*1000));
    }

    private void cancelGuide() {
        if (!mIsGuide)
            return;
        Log.d(TAG, "cancelGuide: ");
        mIsGuide = false;
        mContentGuideLayout.setVisibility(View.GONE);

        for (int i = 0; i < mDataList.size(); i++) {
            BaseModel model = mDataList.get(i);
            model.cellType = Constant.CellType.CHECKBOX;
        }
        mAdapter.setBaseObjects(mDataList);
        mAdapter.notifyDataSetInvalidated();
    }

    private final Handler mHandler = new Handler(Looper.myLooper()) {
        @SuppressLint("NotifyDataSetChanged")
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == Constant.MSG_DB_OBSERVER_RINGTONE) {
                checkDownloadingStatus();
            }
        }
    };

    private void playRingtone(int position) {
        RingtoneModel before = mRingtoneList.get(selectIndex);
        if (before.ringtone.isPlaying()) {
            Log.d(TAG, "playRingtone: cur playing");
            before.ringtone.stop();
        }

        RingtoneModel model = mRingtoneList.get(position);
        model.ringtone.play();
    }

    private void saveRingtone(int position) {
        RingtoneModel model = mRingtoneList.get(position);
        DataManager.setRingTone(position, model.uri);
    }

    private void saveResult(int position) {
        Intent intent = new Intent();
        intent.setAction(Constant.INTENT_RESULT_ACTION);
        intent.putExtra(Constant.INTENT_RESULT_VALUE, position);
        setResult(RESULT_OK, intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //监听数据库
        if (!Macros.DEBUG) {
            mRingtonesContentObserver = new RingtonesContentObserver(mHandler);
            getContentResolver().registerContentObserver(Uri.parse(MetaData.DB_GOPLAY_RINGTONES), true, mRingtonesContentObserver);
        }

        //检查是否有新铃声需要下载
        checkNewRingtone();
    }

    @Override
    protected void onPause() {
        Log.d(TAG, "onPause: ");
        super.onPause();

        if (Macros.DEBUG)
            return;

        if (selectIndex < mRingtoneList.size()) {
            RingtoneModel before = mRingtoneList.get(selectIndex);
            if (before.ringtone.isPlaying()) {
                before.ringtone.stop();
            }
        }

        if (!Macros.DEBUG) {
            if (mRingtonesContentObserver != null) {
                getContentResolver().unregisterContentObserver(mRingtonesContentObserver);
                mRingtonesContentObserver = null;
            }
        }

        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }

        if (mNewRingtoneFragment != null) {
            mNewRingtoneFragment.dismissAllowingStateLoss();
            mNewRingtoneFragment = null;
        }
    }
}