/*
 * Copyright (C) 2016 Jorge Ruesga
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ruesga.rview.fragments;

import android.content.Context;
import android.os.Bundle;

import com.ruesga.rview.gerrit.GerritApi;
import com.ruesga.rview.gerrit.model.ChangeInfo;
import com.ruesga.rview.gerrit.model.ChangeOptions;
import com.ruesga.rview.gerrit.model.RelatedChangeAndCommitInfo;
import com.ruesga.rview.misc.ModelHelper;
import com.ruesga.rview.preferences.Constants;

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

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

public class RevisionRelatedChangesFragment extends ChangeListFragment {

    private static final List<ChangeOptions> OPTIONS = new ArrayList<ChangeOptions>() {{
        add(ChangeOptions.DETAILED_ACCOUNTS);
        add(ChangeOptions.LABELS);
        add(ChangeOptions.REVIEWED);
    }};

    public static RevisionRelatedChangesFragment newInstance(int legacyChangeId, String revisionId) {
        RevisionRelatedChangesFragment fragment = new RevisionRelatedChangesFragment();
        Bundle arguments = new Bundle();
        arguments.putString(Constants.EXTRA_LEGACY_CHANGE_ID, String.valueOf(legacyChangeId));
        arguments.putString(Constants.EXTRA_REVISION_ID, revisionId);
        fragment.setArguments(arguments);
        return fragment;
    }

    @SuppressWarnings("ConstantConditions")
    public Observable<List<ChangeInfo>> fetchChanges(Integer count, Integer start) {
        final String legacyChangeId =  getArguments().getString(Constants.EXTRA_LEGACY_CHANGE_ID);
        final String revisionId = getArguments().getString(Constants.EXTRA_REVISION_ID);
        final Context ctx = getActivity();
        final GerritApi api = ModelHelper.getGerritApi(ctx);
        return Observable.zip(
                Observable.just(getCurrentData()),
                Observable.fromCallable(() -> fetchChanges(api,
                        api.getChangeRevisionRelatedChanges(
                                legacyChangeId, revisionId).toBlocking().first().changes)),
                Observable.just(0),
                this::combineChanges
            )
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread());
    }

    @Override
    public void fetchNewItems() {
        getChangesLoader().restart(0, 0);
    }

    @Override
    public void fetchMoreItems() {
        // This is not used here
    }

    @Override
    boolean hasMoreItems(int size, int expected) {
        return false;
    }

    private List<ChangeInfo> fetchChanges(GerritApi api, List<RelatedChangeAndCommitInfo> related) {
        List<ChangeInfo> c = new ArrayList<>(related.size());
        for (RelatedChangeAndCommitInfo r : related) {
            c.add(api.getChange(String.valueOf(r.changeNumber), OPTIONS)
                    .toBlocking().first());
        }
        return c;
    }
}

@@ -732,16 +732,67 @@
 ritApi;%0A
+import com.ruesga.rview.gerrit.filter.ChangeQuery;%0A
 import c
@@ -3357,32 +3357,78 @@
  r : related) %7B%0A
+            if (r.changeNumber != null) %7B%0A    
             c.ad
@@ -3504,16 +3504,20 @@
         
+   
+ 
 .toBlock
@@ -3528,24 +3528,362 @@
 ).first());%0A
+            %7D else %7B%0A                ChangeQuery query = new ChangeQuery().commit(r.commit.commit);%0A                List%3CChangeInfo%3E changes = api.getChanges(query, 1, 0, OPTIONS).toBlocking().first();%0A                if (changes != null && !changes.isEmpty()) %7B%0A                    c.add(changes.get(0));%0A                %7D%0A            %7D%0A
         %7D%0A  

Handle some rare cases where legacyChangeId is not returned. Search by commit hash in that cases.