package com.sheep.gamegroup.helper;

import android.app.Activity;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import com.sheep.gamegroup.model.api.IDownload;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.DialogConfig;
import com.sheep.gamegroup.model.entity.Applications;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.util.DownloadTextUtl;
import com.sheep.gamegroup.util.DownloadUtil;
import com.sheep.gamegroup.util.TimeUtil;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.G;

import java.util.Locale;

import io.reactivex.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import io.reactivex.schedulers.Schedulers;

import static com.sheep.gamegroup.util.UMConfigUtils.Event.FIND_APP;

/**
 * Created by realicing on 2018/6/29.
 * realicing@sina.com
 */
public class FindAppHelper {
    private DownloadHelper downloadHelper = new DownloadHelper();

    public DownloadHelper getDownloadHelper() {
        return downloadHelper;
    }

    public void updateState(int status) {
        downloadHelper.updateState(status);
    }

    public void updateDownloadTaskView(final Activity activity, final IDownload iTask, final TextView down_tv) {
        updateDownloadTaskView(activity, iTask, down_tv, 0);
    }

    public void updateDownloadTaskView(final Activity activity, final IDownload iTask, final TextView down_tv, int type) {
        downloadHelper.updateDownloadTaskView(activity, iTask, down_tv, new Action1<Object>() {
            @Override
            public void call(Object object) {
                boolean installed = object instanceof Integer && DownloadUtil.STATUS_INIT != (int) object;//-1 点击下载按钮的回调;其它状态直接回调不需要点击按钮
                boolean downloadLinkError = object instanceof Boolean && !(boolean) object;//false 下载地址错误会传false过来
                if (installed || downloadLinkError) {
                    if (iTask instanceof Applications) {
                        Applications findApp = (Applications) iTask;
                        recordAppDownloads(activity, findApp, null);
                        FIND_APP.onEvent("application_id", findApp.getId(), "action", down_tv.getText());
                    }
                }
            }
        }, type);
    }

    /**
     * 更新预约下载状态与响应点击
     *
     * @param activity
     * @param findApp
     * @param reservation_tv
     */
    public void updateReservationView(final Activity activity, final Applications findApp, final TextView reservation_tv) {
        final boolean showSimpleText = reservation_tv.getText().length() < 4;
        if (findApp.isCanRecord()) {
            reservation_tv.setEnabled(true);
            reservation_tv.setText(DownloadTextUtl.getReservationText(showSimpleText));
            reservation_tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    FIND_APP.onEvent("application_id", findApp.getId(), "action", "预约下载");
                    reservation_tv.setEnabled(false);
                    recordAppDownloads(activity, findApp, reservation_tv);
                }
            });
        } else {
            reservation_tv.setEnabled(false);
            reservation_tv.setText(DownloadTextUtl.getHasReservationText(showSimpleText));
        }
    }

    public void updateReservationView(final Activity activity, final Applications gameApp, final TextView reservation_tv, int type) {
        final boolean showSimpleText = reservation_tv.getText().length() < 4;
        if (gameApp.isCanRecord()) {
            reservation_tv.setEnabled(true);
            reservation_tv.setText(DownloadTextUtl.getReservationText(showSimpleText));
            if (type == 0) {
                reservation_tv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        FIND_APP.onEvent("application_id", gameApp.getId(), "action", "预约下载");
                        reservation_tv.setEnabled(false);
                        recordAppDownloads(activity, gameApp, reservation_tv);
                    }
                });
            }

        } else {
            reservation_tv.setEnabled(false);
            reservation_tv.setText(DownloadTextUtl.getHasReservationText(showSimpleText));
        }
    }


    /**
     * 点击预约下载与立即下载时，需要调用这个接口记录到服务器
     *
     * @param findApp
     */
    private void recordAppDownloads(final Activity activity, final Applications findApp, final TextView textView) {
        SheepApp.getInstance().getNetComponent().getApiService().recordAppDownloads(findApp.getId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        final boolean showSimpleText = textView != null && textView.getText().length() < 4;
                        findApp.setRecord(2);//设置为不可记录
                        if (findApp.isCanDownload()) {
                            //提交下载成功
                            if (textView != null)
                                textView.setEnabled(true);
                        } else {//提交预约成功
                            if (textView != null) {
                                textView.setEnabled(false);
                                textView.setText(DownloadTextUtl.getHasReservationText(showSimpleText));
                            }
                            ViewUtil.showMsgDialog(activity, new DialogConfig().setTitle("预约成功")
                                    .setMsg(String.format(Locale.CHINA, "请在%s准时到小绵羊下载哦", TimeUtil.TimeStamp2Date(findApp.getDownload_at(), "yyyy年MM月dd日HH时mm分")))
                                    .setMsgGravity(Gravity.START).setBtnLeftText("我知道了"));
                        }
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        if (!findApp.isCanDownload()) {
                            G.showToast("预约失败");
                        }
                        if (textView != null)
                            textView.setEnabled(true);
                    }
                });
    }
}
