package com.jonasgerdes.schauburgr.usecase.movie_detail;

import com.jonasgerdes.schauburgr.App;
import com.jonasgerdes.schauburgr.model.Movie;
import com.jonasgerdes.schauburgr.model.Screening;
import com.jonasgerdes.schauburgr.network.url.UrlProvider;

import java.util.Date;

import javax.inject.Inject;

import io.realm.Realm;
import io.realm.RealmResults;

/**
 * @author Jonas Gerdes <dev@jonasgerdes.com>
 * @since 29.03.2017
 */

public class MovieDetailPresenter implements MovieDetailContract.Presenter {

    @Inject
    Realm mRealm;

    @Inject
    UrlProvider mUrlProvider;

    private MovieDetailContract.View mView;

    @Override
    public void attachView(MovieDetailContract.View view) {
        App.getAppComponent().inject(this);
        mView = view;
        mView.setPresenter(this);
    }

    @Override
    public void detachView() {
        mRealm.removeAllChangeListeners();
        mRealm.close();
    }


    @Override
    public void onStartWithMovieId(String movieId) {
        Movie movie = mRealm.where(Movie.class)
                .equalTo("resourceId", movieId)
                .findFirst();
        mView.showMovie(movie);
        RealmResults<Screening> screenings = movie.getScreenings()
                .where()
                .greaterThan("startDate", new Date())
                .findAll();
        mView.showScreenings(screenings);
    }

    @Override
    public void onScreeningSelected(Screening screening) {
        String url = mUrlProvider.getReservationPageUrl(screening);
        mView.openWebpage(url);
    }
}

@@ -353,16 +353,38 @@
 Results;
+%0Aimport io.realm.Sort;
 %0A%0A/**%0A *
@@ -1176,16 +1176,162 @@
 movie);%0A
+        //sometimes there are same movies with different extras (3D, atmos)%0A        //find all screenings of movies regardless of extra-splitting%0A
         
@@ -1372,16 +1372,20 @@
  = m
-ovie.get
+Realm.where(
 Scre
@@ -1389,18 +1389,22 @@
 creening
+.clas
 s
-(
 )%0A      
@@ -1418,15 +1418,48 @@
    .
-wher
+equalTo(%22movie.title%22, movie.getTitl
 e()
+)
 %0A   
@@ -1533,17 +1533,50 @@
 .findAll
-(
+Sorted(%22startDate%22, Sort.ASCENDING
 );%0A     

Combine screenings of movies that are actually the same