package ca.etsmtl.applets.seemobile.presenter;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.util.Log;

import com.j256.ormlite.dao.Dao;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.inject.Inject;

import ca.etsmtl.applets.seemobile.Injector;
import ca.etsmtl.applets.seemobile.model.ListePostulations;
import ca.etsmtl.applets.seemobile.model.Postulation;
import ca.etsmtl.applets.seemobile.model.Session;
import ca.etsmtl.applets.seemobile.service.DatabaseHelper;
import ca.etsmtl.applets.seemobile.service.SEEService;
import ca.etsmtl.applets.seemobile.utils.AuthenticationInterceptor;
import ca.etsmtl.applets.seemobile.utils.Constants;
import ca.etsmtl.applets.seemobile.utils.Synchronizer;
import ca.etsmtl.applets.seemobile.view.PostulationView;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by gnut3ll4 on 20/12/15.
 */
public class PostulationPresenter implements IPostulationPresenter {

    private PostulationView postulationView;

    @Inject
    SEEService seeService;

    @Inject
    DatabaseHelper databaseHelper;

    @Inject
    AccountManager accountManager;

    @Inject
    AuthenticationInterceptor authenticationInterceptor;

    private Synchronizer<Postulation> postulationSynchronizer;
    private Dao<Postulation, ?> postulationDao;

    public PostulationPresenter(PostulationView postulationView) {
        this.postulationView = postulationView;
        Injector.INSTANCE.getServiceComponent().inject(this);

        try {
            postulationDao = databaseHelper.getDao(Postulation.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        postulationSynchronizer = new Synchronizer<>(postulationDao);

    }

    @Override
    public void onResume() {

        try {
            postulationView.setItems(postulationDao.queryForAll());
        } catch (SQLException e) {
            e.printStackTrace();
        }

        postulationView.showProgress();

        Session currentSession = new Session();
        Observable<ListePostulations> postulationsCurrentSession = seeService.getApi()
                .getPostulations(currentSession);
        Observable<ListePostulations> postulationsPreviousSession = seeService.getApi()
                .getPostulations(currentSession.getSessionBefore());


        Observable.zip(postulationsCurrentSession, postulationsPreviousSession,
                (listePostulations1, listePostulations2) -> {
                    listePostulations1.addAll(listePostulations2);
                    return listePostulations1;
                })
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .flatMap(listePostulations -> {
                    if (listePostulations.getErreur().getCode() != 1000) {
                        accountManager.invalidateAuthToken(Constants.ACCOUNT_TYPE, authenticationInterceptor.getAuthToken());
                        return Observable.error(new Exception("Request didn't succeed"));
                    } else {
                        return Observable.just(listePostulations.getPostulationList());
                    }
                })
                .retry(1)
                .doOnNext(postulationSynchronizer::synchronize)
                .subscribe(new Observer<List<Postulation>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.d("PostulationPresenter", "e:" + e);
                        postulationView.hideProgress();
                    }

                    @Override
                    public void onNext(List<Postulation> postulations) {
                        postulationView.setItems(postulations);
                        postulationView.hideProgress();
                    }
                });


    }

    @Override
    public void onItemClicked(int position) {
        postulationView.showMessage(String.format("Position %d clicked", position + 1));
    }

}

@@ -2327,48 +2327,16 @@
 n = 
-seeService.getApi()%0A                .get
+getListe
 Post
@@ -2433,48 +2433,16 @@
 n = 
-seeService.getApi()%0A                .get
+getListe
 Post
@@ -2486,18 +2486,16 @@
 ore());%0A
-%0A%0A
         
@@ -2922,361 +2922,8 @@
 s -%3E
- %7B%0A                    if (listePostulations.getErreur().getCode() != 1000) %7B%0A                        accountManager.invalidateAuthToken(Constants.ACCOUNT_TYPE, authenticationInterceptor.getAuthToken());%0A                        return Observable.error(new Exception(%22Request didn't succeed%22));%0A                    %7D else %7B%0A                        return
  Obs
@@ -2978,49 +2978,8 @@
 t())
-;%0A                    %7D%0A                %7D
 )%0A  
@@ -3790,24 +3790,24 @@
 position) %7B%0A
-
         post
@@ -3890,10 +3890,678 @@
 %0A    %7D%0A%0A
+    public Observable%3CListePostulations%3E getListePostulations(Session session) %7B%0A        return seeService.getApi()%0A                .getPostulations(session)%0A                .flatMap(listePostulations -%3E %7B%0A                    if (listePostulations.getErreur().getCode() != 1000) %7B%0A                        accountManager.invalidateAuthToken(Constants.ACCOUNT_TYPE, authenticationInterceptor.getAuthToken());%0A                        return Observable.error(new Exception(%22Request didn't succeed%22));%0A                    %7D else %7B%0A                        return Observable.just(listePostulations);%0A                    %7D%0A                %7D)%0A                .retry(1);%0A    %7D%0A%0A
 %7D%0A

Fix refresh cookie error