package com.philisense.rdgo.viewModel;

import android.content.Context;

import com.philisense.rdgo.bean.OError;
import com.philisense.rdgo.bean.request.ReplaceRequestBean;
import com.philisense.rdgo.bean.response.BaseBean;
import com.philisense.rdgo.db.DBFactory;
import com.philisense.rdgo.db.UserDb;
import com.philisense.rdgo.http.HttpClient;
import com.philisense.rdgo.http.RequestImpl;
import com.philisense.rdgo.http.cache.ACache;
import com.philisense.rdgo.util.Constant;

import java.util.ArrayList;
import java.util.List;

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

/**
 * Created by shaop on 2018/1/9.
 */

public class ReplaceViewModel {
    private Context context;

    public ReplaceViewModel(Context context) {
        this.context = context;
    }

    public void replaceAction(String oldBoxId, String newBoxId, List<String> bottles, RequestImpl<String> listener) {

        List<ReplaceRequestBean.BottleList> bottleLists = new ArrayList<>();
        for (String bottle: bottles) {
            ReplaceRequestBean.BottleList bottlbean = new ReplaceRequestBean.BottleList();
            bottlbean.setBottleId(bottle);
            bottleLists.add(bottlbean);
        }

        UserDb userDb = DBFactory.getUserInfo(context);

        ReplaceRequestBean bean = new ReplaceRequestBean();
        bean.setAccessToken(ACache.get(context).getAsString(Constant.ACCESSTOKEN));
        bean.setNewBoxId(newBoxId);
        bean.setOldBoxId(oldBoxId);
        bean.setBottleList(bottleLists);
        bean.setAccount(userDb.getAccount());
        bean.setName(userDb.getName());
        bean.setWarehouse(userDb.getWarehouse());
        bean.setWarehouseCode(userDb.getWarehouseCode());

        HttpClient.Builder.getBaseService()
                .replaceAction(bean)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BaseBean value) {
                        if (value.getSuccess() == 0){
                            listener.loadSuccess(value.getMessage());
                        }else {
                            listener.loadFailed(new OError(value.getSuccess(), value.getMessage()));
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        listener.loadFailed(new OError(3,e.getMessage()));
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
