package com.philisense.rdgo.viewModel;

import android.content.Context;
import android.util.Log;

import com.jakewharton.rxbinding2.InitialValueObservable;
import com.philisense.rdgo.bean.OError;
import com.philisense.rdgo.bean.request.LoginRequestBean;
import com.philisense.rdgo.bean.response.LoginBean;
import com.philisense.rdgo.bean.response.UserListBean;
import com.philisense.rdgo.db.DBFactory;
import com.philisense.rdgo.db.DBImpl;
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 com.philisense.rdgo.util.MD5Util;

import java.util.ArrayList;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;


/**
 * Created by shaop on 2017/12/13.
 */

public class LoginViewModel {

    public Observable<Boolean> loginValidation;

    private Context context;
    private String username;
    private String password;
    private String uuid;

    public LoginViewModel(String uuid,Context context,InitialValueObservable<CharSequence> observableUsername,InitialValueObservable<CharSequence> observablePassword) {
        this.context = context;

        password = "";
        username = "";
        this.uuid=uuid;
        observablePassword.subscribe(new Consumer<CharSequence>() {
            @Override
            public void accept(CharSequence charSequence) throws Exception {
                password = charSequence.length()>0?charSequence+"":"";
            }
        });

        observableUsername.subscribe(new Consumer<CharSequence>() {
            @Override
            public void accept(CharSequence charSequence) throws Exception {
                username = charSequence.length()>0?charSequence+"":"";
            }
        });

        loginValidation = Observable.combineLatest(observableUsername, observablePassword, new BiFunction<CharSequence, CharSequence, Boolean>() {
            @Override
            public Boolean apply(CharSequence username, CharSequence password) throws Exception {
                return username.length()>0 && password.length()>0;
            }
        });
    }

    public void getUserList(int index, RequestImpl<ArrayList<String>> listener) {
        HttpClient.Builder.getBaseService()
                .getUserList()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<UserListBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(UserListBean value) {
                        if (value.getSuccess()!=0) {
                            listener.loadFailed(new OError(value.getSuccess(), value.getMessage()));
                        }else {
                            ArrayList<String> list = new ArrayList<>();
                            for (UserListBean.ListBean bean : value.getList()) {
                                list.add(bean.getAccount());
                            }
                            Log.e("tag",list.size()+"");
                            listener.loadSuccess(list);
                        }
                    }

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

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public void loginAction(final RequestImpl listener){
//        System.out.println(uuid+"pppppppp");
         HttpClient.Builder.getBaseService()
                        .login(new LoginRequestBean(username, MD5Util.getMD5(password),uuid))
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Observer<LoginBean>() {
                            @Override
                            public void onSubscribe(Disposable d) {

                            }

                            @Override
                            public void onNext(LoginBean value) {
                                if (value.getSuccess()!=0) {
                                    listener.loadFailed(new OError(value.getSuccess(), value.getMessage()));
                                }else {
                                    // 缓存用户基本信息
                                    ACache aCache = ACache.get(context);
                                    aCache.put(Constant.ACCESSTOKEN, value.getData().getToken()+"");
                                    aCache.put(Constant.USERID, value.getData().get_id());

                                    // 把用户信息存入数据库，便于统计登录此 pda 的用户信息
                                    DBFactory.UpdateUser(value, new DBImpl() {
                                        @Override
                                        public void loadSuccess() {
                                            listener.loadSuccess(value);
                                        }
                                        @Override
                                        public void loadFailed(String error) {
                                            listener.loadFailed(new OError(Constant.DBErrorCode,error));
                                        }
                                    });
                                }
                            }

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

                            @Override
                            public void onComplete() {

                            }
                        });

    }
}
