package com.revoapp.calendar;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.revoapp.api.database.calendar.pojo.Events;
import com.revoapp.api.database.calendar.pojo.Pills;
import com.revoapp.api.utils.DateTimeConvert;
import com.revoapp.api.utils.Utils;
import com.revoapp.calendar.adapter.DayEventsAdapter;
import com.revoapp.calendar.adapter.DayMedicineAdapter;
import com.revoapp.calendar.database.Category;
import com.revoapp.calendar.database.DatabaseHandler;
import com.revoapp.calendar.database.PillsDatabaseHandler;
import com.revoapp.calendar.dialogs.AddEventDialog;
import com.revoapp.calendar.dialogs.DayDetailsOptionListDialog;
import com.revoapp.calendar.dialogs.EventsContextDialog;
import com.revoapp.calendar.helper.DataHelper;
import com.revoapp.calendar.helper.ThemeHelper;
import com.revoapp.calendar.service.EventAlarmServices;
import com.revoapp.calendarapp.R;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.Locale;

public class DayActivity extends ParentActivity {
    private Context context;
    private TextView monthInfo;
    private Calendar globalCalendar;
    private ListView medicineList;
    private DayMedicineAdapter adapter;
    private ArrayList<Events> eventsListTmp;
    private ListView eventsListView;
    private DayEventsAdapter eventsAdapter;
    private TextView emptyDay;
    private DatabaseHandler database;
    private DayActivity dayActivity;
    private EventsContextDialog eventsContextDialog;
    private boolean isEmpty, emptyEvents, emptyMedicines;
    public ArrayList<Category> optionList;
    private DayDetailsOptionListDialog dayComboBox;
    private Button comboBoxbutton;
    public int selectedOption = -1;
    private int selectedOptionId = -1;
    private int dialogPosition;
    private AddEventDialog addEventDialog;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.day_activity);

        dayActivity = this;
        context = this;

        Utils.disableLockScreen(this);

        if(savedInstanceState != null){
            MonthActivity.currentYear = savedInstanceState.getInt("year");
            MonthActivity.selectedDay = savedInstanceState.getInt("day");
            MonthActivity.currentMonth = savedInstanceState.getInt("month");
        }

        init();
        initCalendar();

        if(savedInstanceState != null){
            if(savedInstanceState.getBoolean("dialogContext")){
                dialogPosition = savedInstanceState.getInt("pos");
                Events event = eventsAdapter.getItem(dialogPosition);
                eventsContextDialog.show(event);
            } else if(savedInstanceState.getBoolean("dialogCombo")){
                dialogPosition = savedInstanceState.getInt("pos");
                dayComboBox.show();
            } else if(savedInstanceState.getBoolean("dialogAdd")){
                addEventDialog = new AddEventDialog(context, dayActivity, savedInstanceState.getInt("numberOfScreen"), savedInstanceState.getStringArrayList("data"), savedInstanceState.getString("title"));
                addEventDialog.show();
//                InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            }
        }
    }

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

        refreshView();

        if (selectedOptionId == -1) {
            hideViews(false, false);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
        if(eventsContextDialog != null){
            if(eventsContextDialog.isShowing()){
                eventsContextDialog.dismiss();
            }
        }
        if(dayComboBox != null){
            if(dayComboBox.isShowing()){
                dayComboBox.dismiss();
            }
        }
        if(addEventDialog != null){
            if(addEventDialog.isShowing()){
                addEventDialog.dismiss();
            }
        }
    }

    @Override
    public void refreshView() {
        init();
        initCalendar();

        CalendarActivity.setTab(CalendarActivity.tabHost.getCurrentTab());
        if (adapter != null)
            adapter.notifyDataSetChanged();
        if (eventsAdapter != null)
            eventsAdapter.notifyDataSetChanged();
    }

    private void init() {
        isEmpty = true;
        emptyEvents = true;
        emptyMedicines = true;

        ImageButton dayLeft = (ImageButton) findViewById(R.id.month_left);
        dayLeft.setBackgroundResource(ThemeHelper.get_button_selector());
        dayLeft.setImageResource(ThemeHelper.get_icon50_arrow_left());
        dayLeft.setOnClickListener(chooseDayListener);

        ImageButton dayRight = (ImageButton) findViewById(R.id.month_right);
        dayRight.setBackgroundResource(ThemeHelper.get_button_selector());
        dayRight.setImageResource(ThemeHelper.get_icon50_arrow_right());
        dayRight.setOnClickListener(chooseDayListener);

        View todayV = (View) findViewById(R.id.today_linear);
        todayV.setBackgroundResource(ThemeHelper.get_button_selector());
        todayV.setOnClickListener(todayListener);

        TextView todayIcon = (TextView) findViewById(R.id.today_icon);
        todayIcon.setBackgroundResource(ThemeHelper.get_icon50_today());
        todayIcon.setText(new GregorianCalendar().get(GregorianCalendar.DAY_OF_MONTH) + "");
        todayIcon.setTextColor(context.getResources().getColorStateList(
                ThemeHelper.get_button_color_selector()));
        todayIcon.setTextSize((int) getResources().getDimension(R.dimen.calendar_header_text));

        TextView todayText = (TextView) findViewById(R.id.today_text);
        todayText.setTextColor(context.getResources().getColorStateList(
                ThemeHelper.get_button_color_selector()));
        todayText.setTextSize((int) getResources().getDimension(R.dimen.calendar_header_text));

        Button addEvent = (Button) findViewById(R.id.add_event);
        addEvent.setOnClickListener(eventAddListener);
        addEvent.setCompoundDrawablesWithIntrinsicBounds(ThemeHelper.get_icon50_add(), 0, 0, 0);

        emptyDay = (TextView) findViewById(R.id.empty_day);

        eventsListTmp = new ArrayList<Events>();

        optionList = new ArrayList<Category>();
        ArrayList<String> categoryName = new ArrayList<String>();
        ArrayList<Integer> categoryIcon = new ArrayList<Integer>(DataHelper.getCollection(DataHelper.get_category_icon_array()));
        Collections.addAll(categoryName, getResources().getStringArray(R.array.options));
        Category c;
        for (int i = 0; i < categoryName.size(); i++) {
            c = new Category();
            c.setText(categoryName.get(i));
            c.setIcon(getResources().getDrawable(categoryIcon.get(i)));
            optionList.add(c);
        }

        dayComboBox = new DayDetailsOptionListDialog(context, dayActivity);

        comboBoxbutton = (Button) findViewById(R.id.comboBoxButton);

        comboBoxbutton.setOnClickListener(comboBoxListener);

        eventsContextDialog = new EventsContextDialog(context, this);

        getEvents();
        hideViews();
        showDefaultView();
    }

    public void setChoosenButtonText(int position) {
        comboBoxbutton.setText(optionList.get(position).getText());
    }

    private void showDefaultView() {
        if (selectedOptionId != -1) {
            loadSelectedOption(selectedOptionId);
        } else {
            if (!emptyEvents)
                loadSelectedOption(1);
            else if (!emptyMedicines)
                loadSelectedOption(0);
        }
    }

    public void loadSelectedOption(int position) {
        selectedOptionId = position;
        switch (position) {
            case 0:
                comboBoxbutton.setText(optionList.get(position).getText());
                comboBoxbutton.setCompoundDrawablesWithIntrinsicBounds(DataHelper.get_category_icon_array()[position], 0, 0, 0);
                hideViews(true, false);
                break;
            case 1:
                comboBoxbutton.setText(optionList.get(position).getText());
                comboBoxbutton.setCompoundDrawablesWithIntrinsicBounds(DataHelper.get_category_icon_array()[position], 0, 0, 0);
                hideViews(false, true);
                break;
        }
    }

    private void hideViews(boolean medicine, boolean events) {
        if (medicine) {
            medicineList.setVisibility(View.VISIBLE);
            eventsListView.setVisibility(View.GONE);
            emptyDay.setVisibility(View.GONE);
            if (emptyMedicines) {
                medicineList.setVisibility(View.GONE);
                emptyDay.setText(R.string.empty_medicine);
                emptyDay.setVisibility(View.VISIBLE);
            }
        }
        if (events) {
            medicineList.setVisibility(View.GONE);
            eventsListView.setVisibility(View.VISIBLE);
            emptyDay.setVisibility(View.GONE);
            if (emptyEvents) {
                eventsListView.setVisibility(View.GONE);
                emptyDay.setText(R.string.empty_day);
                emptyDay.setVisibility(View.VISIBLE);
            }
        }
        if (!medicine && !events) {
            if (medicineList != null)
                medicineList.setVisibility(View.GONE);
            if (eventsListView != null)
                eventsListView.setVisibility(View.GONE);
        }
    }

    private void getEvents() {
        isEmpty = true;
        emptyEvents = true;
        emptyMedicines = true;
        Calendar pillCall = Calendar.getInstance();
        pillCall.set(MonthActivity.currentYear, MonthActivity.currentMonth, MonthActivity.selectedDay);
        pillCall.set(Calendar.HOUR_OF_DAY, 0);
        pillCall.set(Calendar.MINUTE, 0);
        pillCall.set(Calendar.SECOND, 0);
        long beginTime = pillCall.getTimeInMillis() / 1000;
        pillCall.set(Calendar.HOUR_OF_DAY, 23);
        pillCall.set(Calendar.MINUTE, 59);
        pillCall.set(Calendar.SECOND, 59);

        PillsDatabaseHandler db = new PillsDatabaseHandler(this);
        ArrayList<Pills> pillsList = db.getAllPillsByDate(beginTime, pillCall.getTimeInMillis() / 1000);
        medicineList = (ListView) findViewById(R.id.medicine_list_view);
        if (!pillsList.isEmpty()) {
            isEmpty = false;
            emptyMedicines = false;

            medicineList.setVisibility(View.VISIBLE);
            medicineList.setDivider(getResources().getDrawable(ThemeHelper.get_separator_list()));
            adapter = new DayMedicineAdapter(context, R.layout.day_medicine_row, pillsList);
            medicineList.setAdapter(adapter);
        }

        database = new DatabaseHandler(context);

        ArrayList<Events> eventsList = database.getAllEvents();
        eventsListTmp.clear();
        eventsListView = (ListView) findViewById(R.id.events_list_view);
        if (!eventsList.isEmpty()) {
            for (Events event : eventsList) {
                if (DateTimeConvert.compareDate(context, event.getDate(),
                        MonthActivity.currentYear, MonthActivity.currentMonth,
                        MonthActivity.selectedDay)) {
                    eventsListTmp.add(event);
                }
            }

            if (!eventsListTmp.isEmpty()) {
                isEmpty = false;
                emptyEvents = false;
                eventsListView.setOnItemLongClickListener(eventOptionListener);
                eventsListView.setVisibility(View.VISIBLE);
                eventsAdapter = new DayEventsAdapter(this, R.layout.dialog_day_events_row, eventsListTmp);
                eventsListView.setAdapter(eventsAdapter);
                eventsListView.setDivider(context.getResources().getDrawable(
                        ThemeHelper.get_separator_list()));
            } else {
                eventsListView.setVisibility(View.GONE);
            }

            if (eventsAdapter != null)
                eventsAdapter.notifyDataSetChanged();
        } else {
            if (eventsListView != null)
                eventsListView.setVisibility(View.GONE);
        }
    }

    @SuppressLint("NewApi")
    private String getDayName() {
        Calendar cal = Calendar.getInstance();
        cal.set(MonthActivity.currentYear, MonthActivity.currentMonth, MonthActivity.selectedDay);

        String date;
        //sr, 16 kwi, 2014
        date = cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()) + ", ";
        date += cal.get(Calendar.DAY_OF_MONTH) + " ";
        date += cal.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.getDefault()) + " ";
        date += cal.get(Calendar.YEAR);
        return date;
    }

    private void initCalendar() {
        globalCalendar = Calendar.getInstance();
        globalCalendar.set(MonthActivity.currentYear, MonthActivity.currentMonth, MonthActivity.selectedDay);

        monthInfo = (TextView) findViewById(R.id.month_info);
        monthInfo.setTextSize((int) getResources().getDimension(R.dimen.calendar_header_text));
        monthInfo.setText(getDayName());
    }

    private void hideViews() {
        if (isEmpty) {
            emptyDay.setVisibility(View.VISIBLE);
        } else {
            emptyDay.setVisibility(View.GONE);
        }
    }

    private OnClickListener comboBoxListener = new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            dayComboBox.show();
        }
    };

    private OnClickListener todayListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            Calendar cur = Calendar.getInstance();
            MonthActivity.currentYear = cur.get(Calendar.YEAR);
            MonthActivity.selectedDay = cur.get(Calendar.DAY_OF_MONTH);
            MonthActivity.currentMonth = cur.get(Calendar.MONTH);

            initCalendar();
            getEvents();
            hideViews();
            showDefaultView();
        }
    };

    private OnClickListener eventAddListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            addEventDialog = new AddEventDialog(context, dayActivity);
            addEventDialog.show();
        }
    };

    public void deleteEvent(Events event) {
        database.deleteEvent(event);
        eventsListTmp.remove(event);
        startAlarmServices();
        refreshView();
        eventsAdapter.notifyDataSetChanged();
    }

    private void startAlarmServices() {
        Intent mServiceIntent = new Intent(context, EventAlarmServices.class);
        mServiceIntent.setAction(EventAlarmServices.CREATE);

        context.startService(mServiceIntent);
    }

    private OnItemLongClickListener eventOptionListener = new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                                       int position, long arg3) {
            Events event = eventsAdapter.getItem(position);
            dialogPosition = position;
            eventsContextDialog.show(event);
            return false;
        }
    };

    private OnClickListener chooseDayListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.month_right) {
                globalCalendar.add(Calendar.DAY_OF_MONTH, 1);
            }
            if (v.getId() == R.id.month_left) {
                globalCalendar.add(Calendar.DAY_OF_MONTH, -1);
            }

            MonthActivity.currentYear = globalCalendar.get(Calendar.YEAR);
            MonthActivity.selectedDay = globalCalendar.get(Calendar.DAY_OF_MONTH);
            MonthActivity.currentMonth = globalCalendar.get(Calendar.MONTH);

            monthInfo.setText(getDayName());
            getEvents();
            hideViews();
            loadSelectedOption(selectedOptionId);
        }
    };

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);
        savedInstanceState.putString("date", getDayName());
        savedInstanceState.putInt("year", MonthActivity.currentYear);
        savedInstanceState.putInt("month", MonthActivity.currentMonth);
        savedInstanceState.putInt("day", MonthActivity.selectedDay);

        if(eventsContextDialog != null){
            if(eventsContextDialog.isShowing()){
                savedInstanceState.putBoolean("dialogContext", true);
                savedInstanceState.putInt("pos", dialogPosition);
            }
        }

        if(dayComboBox != null){
            if(dayComboBox.isShowing()){
                savedInstanceState.putBoolean("dialogCombo", true);
            }
        }

        if(addEventDialog != null){
            if(addEventDialog.isShowing()){
                savedInstanceState.putBoolean("dialogAdd", true);
                savedInstanceState.putInt("numberOfScreen", addEventDialog.getNumberOfScreen());
                savedInstanceState.putStringArrayList("data", addEventDialog.getData());
                savedInstanceState.putString("title", addEventDialog.getTitle());
            }
        }
    }
}