/*
 * Copyright 2015 Red Hat, Inc. and/or its affiliates
 * and other contributors as indicated by the @author tags.
 *
 * 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 org.hawkular.client.android.fragment;

import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import org.hawkular.client.android.R;
import org.hawkular.client.android.adapter.ResourcesAdapter;
import org.hawkular.client.android.backend.BackendClient;
import org.hawkular.client.android.backend.model.Environment;
import org.hawkular.client.android.backend.model.Resource;
import org.hawkular.client.android.backend.model.Tenant;
import org.hawkular.client.android.util.Fragments;
import org.hawkular.client.android.util.Intents;
import org.hawkular.client.android.util.ViewDirector;
import org.jboss.aerogear.android.pipe.callback.AbstractFragmentCallback;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import icepick.Icepick;
import icepick.Icicle;
import timber.log.Timber;

public final class ResourcesFragment extends Fragment implements AdapterView.OnItemClickListener {
    @Bind(R.id.list)
    ListView list;

    @Icicle
    @Nullable
    ArrayList<Resource> resources;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle state) {
        return inflater.inflate(R.layout.fragment_list, container, false);
    }

    @Override
    public void onActivityCreated(Bundle state) {
        super.onActivityCreated(state);

        setUpState(state);

        setUpBindings();

        setUpList();

        setUpResources();
    }

    private void setUpState(Bundle state) {
        Icepick.restoreInstanceState(this, state);
    }

    private void setUpBindings() {
        ButterKnife.bind(this, getView());
    }

    private void setUpList() {
        list.setOnItemClickListener(this);
    }

    @OnClick(R.id.button_retry)
    public void setUpResources() {
        if (resources == null) {
            showProgress();

            BackendClient.of(this).getResources(getEnvironment(), new ResourcesCallback());
        } else {
            setUpResources(resources);
        }
    }

    private void showProgress() {
        ViewDirector.of(this).using(R.id.animator).show(R.id.progress);
    }

    private Tenant getTenant() {
        return getArguments().getParcelable(Fragments.Arguments.TENANT);
    }

    private Environment getEnvironment() {
        return getArguments().getParcelable(Fragments.Arguments.ENVIRONMENT);
    }

    private void setUpResources(List<Resource> resources) {
        this.resources = new ArrayList<>(resources);

        sortResources(this.resources);

        list.setAdapter(new ResourcesAdapter(getActivity(), this.resources));

        showList();
    }

    private void sortResources(List<Resource> resources) {
        Collections.sort(resources, new ResourcesComparator());
    }

    private void showList() {
        ViewDirector.of(this).using(R.id.animator).show(R.id.list);
    }

    private void showMessage() {
        ViewDirector.of(this).using(R.id.animator).show(R.id.message);
    }

    private void showError() {
        ViewDirector.of(this).using(R.id.animator).show(R.id.error);
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        Resource resource = getResourcesAdapter().getItem(position);

        startMetricTypesActivity(resource);
    }

    private ResourcesAdapter getResourcesAdapter() {
        return (ResourcesAdapter) list.getAdapter();
    }

    private void startMetricTypesActivity(Resource resource) {
        Intent intent = Intents.Builder.of(getActivity()).buildMetricsIntent(getTenant(), getEnvironment(), resource);
        startActivity(intent);
    }

    @Override
    public void onSaveInstanceState(Bundle state) {
        super.onSaveInstanceState(state);

        tearDownState(state);
    }

    private void tearDownState(Bundle state) {
        Icepick.saveInstanceState(this, state);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

        tearDownBindings();
    }

    private void tearDownBindings() {
         ButterKnife.unbind(this);
    }

    private static final class ResourcesCallback extends AbstractFragmentCallback<List<Resource>> {
        @Override
        public void onSuccess(List<Resource> resources) {
            if (!resources.isEmpty()) {
                getResourcesFragment().setUpResources(resources);
            } else {
                getResourcesFragment().showMessage();
            }
        }

        @Override
        public void onFailure(Exception e) {
            Timber.d("Resources fetching failed.");

            getResourcesFragment().showError();
        }

        private ResourcesFragment getResourcesFragment() {
            return (ResourcesFragment) getFragment();
        }
    }

    private static final class ResourcesComparator implements Comparator<Resource> {
        @Override
        public int compare(Resource leftResource, Resource rightResource) {
            String leftResourceTypeId = leftResource.getType().getId();
            String rightResourceTypeId = rightResource.getType().getId();

            String leftResourceUrl = leftResource.getProperties().getUrl();
            String rightResourceUrl = rightResource.getProperties().getUrl();

            if (leftResourceTypeId.equals(rightResourceTypeId)) {
                return leftResourceUrl.compareTo(rightResourceUrl);
            } else {
                return leftResourceTypeId.compareTo(rightResourceTypeId);
            }
        }
    }
}

@@ -3477,16 +3477,32 @@
 yList%3C%3E(
+filterResources(
 resource
@@ -3495,32 +3495,33 @@
 urces(resources)
+)
 ;%0A%0A        sortR
@@ -3618,32 +3618,32 @@
 s.resources));%0A%0A
-
         showList
@@ -3645,32 +3645,568 @@
 wList();%0A    %7D%0A%0A
+    private List%3CResource%3E filterResources(List%3CResource%3E resources) %7B%0A        // Filter resources without properties set.%0A        // This is mostly a hack at this point because of not standardized properties.%0A%0A        List%3CResource%3E filteredResources = new ArrayList%3C%3E();%0A%0A        for (Resource resource : resources) %7B%0A            if ((resource.getProperties() != null) && (resource.getProperties().getUrl() != null)) %7B%0A                filteredResources.add(resource);%0A            %7D%0A        %7D%0A%0A        return filteredResources;%0A    %7D%0A%0A
     private void

Add resources filtering.