package com.nmakademija.nmaakademija.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.nmakademija.nmaakademija.R;
import com.nmakademija.nmaakademija.adapter.ScheduleAdapter;
import com.nmakademija.nmaakademija.adapter.ScheduleSectionsAdapter;
import com.nmakademija.nmaakademija.api.API;
import com.nmakademija.nmaakademija.entity.ScheduleEvent;
import com.nmakademija.nmaakademija.utils.AppEvent;
import com.nmakademija.nmaakademija.utils.Error;
import com.nmakademija.nmaakademija.utils.NMAPreferences;
import com.nmakademija.nmaakademija.utils.ScheduleEventComparator;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ScheduleFragment extends Fragment {

    private RecyclerView scheduleRecyclerView;
    private ArrayList<ScheduleEvent> scheduleEvents;

    private String EXTRA_EVENTS = "schedule_events";

    public static ScheduleFragment getInstance() {
        return new ScheduleFragment();
    }

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

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if(savedInstanceState != null)
            scheduleEvents = savedInstanceState.getParcelableArrayList(EXTRA_EVENTS);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putParcelableArrayList(EXTRA_EVENTS, scheduleEvents);

        super.onSaveInstanceState(outState);
    }

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

        AppEvent.getInstance(getContext()).trackCurrentScreen(getActivity(), "open_schedules");

        scheduleRecyclerView = (RecyclerView) getView().findViewById(R.id.schedule_list);

        if(scheduleEvents == null)
            getScheduleEvents();
        else
            setScheduleItems();
    }

    private void getScheduleEvents() {
        API.nmaService.getEvents().enqueue(new Callback<List<ScheduleEvent>>() {
            @Override
            public void onResponse(Call<List<ScheduleEvent>> call,
                                   Response<List<ScheduleEvent>> response) {
                List<ScheduleEvent> scheduleEventsList = response.body();
                int sectionId = NMAPreferences.getSection(getContext());
                scheduleEvents = new ArrayList<>();
                for (ScheduleEvent s : scheduleEventsList) {
                    if (s.getSectionId() == 0 || s.getSectionId() == sectionId) {
                        scheduleEvents.add(s);
                    }
                }
                Collections.sort(scheduleEvents, new ScheduleEventComparator());
                setScheduleItems();
            }

            @Override
            public void onFailure(Call<List<ScheduleEvent>> call, Throwable t) {
                Error.getData(getView(), new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        getScheduleEvents();
                    }
                });
            }
        });
    }

    private void setScheduleItems() {
        if (isAdded()) {

            ScheduleAdapter adapter = new ScheduleAdapter(getContext(), scheduleEvents);
            scheduleRecyclerView.setAdapter(adapter);

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.US);

            String lastScheduleDay = "";
            List<ScheduleSectionsAdapter.Section> sections = new ArrayList<>();
            int position = 0, position1 = 0;

            Date now = new Date();

            for (int i = 0; i < scheduleEvents.size(); i++) {
                Date date = scheduleEvents.get(i).getDate();
                String dateString = dateFormat.format(date);

                if (!lastScheduleDay.equals(dateString)) {
                    lastScheduleDay = dateString;
                    sections.add(new ScheduleSectionsAdapter.Section(i, dateString));
                    if (date.before(now)) {
                        position1++;
                    }
                }
                if (date.before(now)) {
                    position = i;
                }
            }

            ScheduleSectionsAdapter.Section[] dummy =
                    new ScheduleSectionsAdapter.Section[sections.size()];
            ScheduleSectionsAdapter mSectionedAdapter = new
                    ScheduleSectionsAdapter(getContext(), adapter);
            mSectionedAdapter.setSections(sections.toArray(dummy));

            scheduleRecyclerView.setAdapter(mSectionedAdapter);
            scheduleRecyclerView.scrollToPosition(position + position1);
        }
    }

}

@@ -1160,33 +1160,36 @@
 %3CScheduleEvent%3E 
-s
+allS
 cheduleEvents;%0A%0A
@@ -1768,16 +1768,17 @@
       if
+ 
 (savedIn
@@ -1802,33 +1802,36 @@
 ll)%0A            
-s
+allS
 cheduleEvents = 
@@ -2017,17 +2017,20 @@
 EVENTS, 
-s
+allS
 cheduleE
@@ -2327,17 +2327,16 @@
 ules%22);%0A
-%0A
         
@@ -2416,16 +2416,90 @@
 e_list);
+%0A    %7D%0A%0A    @Override%0A    public void onStart() %7B%0A        super.onStart();
 %0A%0A      
@@ -2502,18 +2502,22 @@
       if
-(s
+ (allS
 cheduleE
@@ -2922,502 +2922,63 @@
     
-List%3CScheduleEvent%3E scheduleEventsList = response.body();%0A                int sectionId = NMAPreferences.getSection(getContext());%0A                scheduleEvents = new ArrayList%3C%3E();%0A                for (ScheduleEvent s : scheduleEventsList) %7B%0A                    if (s.getSectionId() == 0 %7C%7C s.getSectionId() == sectionId) %7B%0A                        scheduleEvents.add(s);%0A                    %7D%0A                %7D%0A                Collections.sort(scheduleEvents, new ScheduleEventComparator
+allScheduleEvents = new ArrayList%3C%3E(response.body
 ());%0A
+%0A
     
@@ -3462,16 +3462,442 @@
 ded()) %7B
+%0A            int sectionId = NMAPreferences.getSection(getContext());%0A            ArrayList%3CScheduleEvent%3E sectionEvents = new ArrayList%3C%3E();%0A%0A            for (ScheduleEvent s : allScheduleEvents) %7B%0A                if (s.getSectionId() == 0 %7C%7C s.getSectionId() == sectionId) %7B%0A                    sectionEvents.add(s);%0A                %7D%0A            %7D%0A            Collections.sort(sectionEvents, new ScheduleEventComparator());
 %0A%0A      
@@ -3963,23 +3963,22 @@
 ext(), s
-chedule
+ection
 Events);
@@ -4359,23 +4359,22 @@
 0; i %3C s
-chedule
+ection
 Events.s
@@ -4416,23 +4416,22 @@
 date = s
-chedule
+ection
 Events.g

Fix section change bug