package com.bezrukov.timesheets.ui.activities;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.bezrukov.timesheets.R;
import com.bezrukov.timesheets.data.TimeEntryRepository;
import com.bezrukov.timesheets.event.TimeEntriesForWeekUpdatedEvent;
import com.bezrukov.timesheets.network.TimeEntriesManager;
import com.bezrukov.timesheets.ui.adapters.TimeEntriesAdapter;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.threeten.bp.DayOfWeek;
import org.threeten.bp.LocalDate;
import org.threeten.bp.format.TextStyle;
import org.threeten.bp.temporal.TemporalAdjusters;

import java.util.Collections;
import java.util.Locale;

import solar.blaz.date.week.WeekDatePicker;

/**
 * Created by user on 16.11.2016.
 */

public class TimeEntriesActivity extends BaseActivity {

    private Toolbar toolbar;
    private RecyclerView recyclerView;
    private FloatingActionButton floatingActionButton;
    private WeekDatePicker weekPicker;
    private TextView monthAndYear;
    private SwipeRefreshLayout refreshLayout;

    private TimeEntriesAdapter adapter;
    private LocalDate currentFirstDay;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();
        setupList();
        initListeners();
        initToolbar();
        setSupportActionBar(toolbar);
    }

    @Override
    protected void onResume() {
        super.onResume();
        updateDataFromMemoryCache();
    }

    private void initViews() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        recyclerView = (RecyclerView) findViewById(R.id.recycler);
        floatingActionButton = (FloatingActionButton) findViewById(R.id.fab);
        weekPicker = (WeekDatePicker) findViewById(R.id.date_picker);
        monthAndYear = (TextView) findViewById(R.id.month_and_year);
        refreshLayout = (SwipeRefreshLayout) findViewById(R.id.refresh_layout);
    }

    private void initListeners() {
        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(TimeEntriesActivity.this, AddTimeEntryActivity.class);
                startActivity(intent);
            }
        });
        weekPicker.setOnWeekChangedListener(new WeekDatePicker.OnWeekChanged() {
            @Override
            public void onItemSelected(LocalDate firstDay) {
                currentFirstDay = firstDay;
                updateCurrentWeek(firstDay);
            }
        });
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                TimeEntriesManager.getInstance().fetchTimeEntriesForWeek(currentFirstDay, false);
            }
        });
        currentFirstDay = LocalDate.now().with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
        TimeEntriesManager.getInstance().fetchTimeEntriesForWeek(currentFirstDay, false);
        updateCurrentWeek(LocalDate.now());
    }

    private void updateCurrentWeek(LocalDate firstDay) {
        String shortMonth = firstDay.getMonth().getDisplayName(TextStyle.SHORT, Locale.getDefault());
        int year = firstDay.getYear();
        monthAndYear.setText(getString(R.string.top_short_date, shortMonth, year));
        adapter.setItems(Collections.EMPTY_LIST);
        TimeEntriesManager.getInstance().fetchTimeEntriesForWeek(currentFirstDay, true);
    }

    private void setupList() {
        adapter = new TimeEntriesAdapter();
        adapter.setItems(Collections.EMPTY_LIST);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);

        ItemTouchHelper.SimpleCallback callback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                return true;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                final int removePosition = viewHolder.getAdapterPosition();
                new AlertDialog.Builder(TimeEntriesActivity.this)
                        .setTitle(R.string.confirm)
                        .setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                TimeEntriesManager.getInstance().removeTimeEntry(adapter.getItemByPosition(removePosition));
                                adapter.removeDataAtPosition(removePosition);
                            }
                        })
                        .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                adapter.notifyDataSetChanged();
                            }
                        }).show();
            }
        };
        ItemTouchHelper helper = new ItemTouchHelper(callback);
        helper.attachToRecyclerView(recyclerView);
    }

    private void initToolbar() {
        toolbar.setTitle(R.string.time_entries_title);
        toolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
        toolbar.setTitleTextColor(getResources().getColor(android.R.color.white));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTimeEntriesForWeekLoaded(TimeEntriesForWeekUpdatedEvent event) {
        if (event.getFirstDayOfWeek().equals(currentFirstDay)) {
            if (event.isSuccess()) {
                updateDataFromMemoryCache();
            } else {
                Toast.makeText(this, R.string.sorry_cant_perform_request, Toast.LENGTH_SHORT).show();
            }
            refreshLayout.setRefreshing(false);
        }
    }

    private void updateDataFromMemoryCache() {
        adapter.setItems(TimeEntryRepository.getInstance().getEntries(currentFirstDay));
    }

}
