package com.casic.dcms.mvp.model.impl;

import com.casic.dcms.bean.ActionResultBean;
import com.casic.dcms.listener.OnActionResultListener;
import com.casic.dcms.mvp.model.IUploadFileModel;
import com.casic.dcms.utils.retrofit.RetrofitServiceManager;

import java.io.File;

import rx.Observable;
import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class UploadFileModelImpl implements IUploadFileModel {

    private final OnActionResultListener actionResultListener;

    public UploadFileModelImpl(OnActionResultListener listener) {
        this.actionResultListener = listener;
    }

    /**
     * {@link IUploadFileModel}
     */
    @Override
    public Subscription sendUploadFileRequest(File file) {
        String fileAbsolutePath = file.getAbsolutePath();
        Observable<ActionResultBean> observable;
        if (fileAbsolutePath.endsWith(".m4a")) {
            observable = RetrofitServiceManager.getAudioUploadResult(file);
        } else if (fileAbsolutePath.endsWith(".mp4")) {
            observable = RetrofitServiceManager.getVideoUploadResult(file);
        } else {
            observable = RetrofitServiceManager.getImageUploadResult(file);
        }
        return observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<ActionResultBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                if (e.getCause() != null) {
                    actionResultListener.onFailure(e);
                }
            }

            @Override
            public void onNext(ActionResultBean resultBean) {
                if (resultBean != null) {
                    actionResultListener.onSuccess(resultBean);
                }
            }
        });
    }
}
