package com.example.nhocg.myseftcalendar.activities;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.nhocg.myseftcalendar.R;
import com.example.nhocg.myseftcalendar.adapter.DayLessonAdapter;
import com.example.nhocg.myseftcalendar.dialog.AddEditDetailCancelDialogFragment;
import com.example.nhocg.myseftcalendar.dialog.AddEditWeekLessonDialogFragment;
import com.example.nhocg.myseftcalendar.exception.NullObjectException;
import com.example.nhocg.myseftcalendar.helper.Constant;
import com.example.nhocg.myseftcalendar.helper.DBHelper;
import com.example.nhocg.myseftcalendar.helper.DBStringHelper;
import com.example.nhocg.myseftcalendar.helper.DateTimeHelper;
import com.example.nhocg.myseftcalendar.helper.FunctionHelper;
import com.example.nhocg.myseftcalendar.helper.ItemTouchHelperCallBackNoMove;
import com.example.nhocg.myseftcalendar.datas.WeekLessonDialogItem;
import com.example.nhocg.myseftcalendar.datas.entities.DayLesson;
import com.example.nhocg.myseftcalendar.datas.entities.Subject;
import com.example.nhocg.myseftcalendar.datas.entities.WeekLesson;
import com.example.recycleview_animator.adapter.SwingBottomInAnimationAdapter;
import com.github.clans.fab.FloatingActionButton;
import com.github.clans.fab.FloatingActionMenu;

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

import static com.example.nhocg.myseftcalendar.dialog.AddEditWeekLessonDialogFragment.AddEditWeekLessonDialogMode.DAY_LESSON_DIALOG_ADD_MODE;
import static com.example.nhocg.myseftcalendar.dialog.AddEditWeekLessonDialogFragment.AddEditWeekLessonDialogMode.WEEK_LESSON_DIALOG_EDIT_MODE;
import static com.example.nhocg.myseftcalendar.dialog.AddEditWeekLessonDialogFragment.WEEK_LESSON_DIALOG_ITEM;
import static com.example.nhocg.myseftcalendar.dialog.AddEditWeekLessonDialogFragment.WEEK_LESSON_DIALOG_ITEM_POS;
import static com.example.nhocg.myseftcalendar.dialog.AddEditWeekLessonDialogFragment.WEEK_LESSON_DIALOG_MODE;
import static com.example.nhocg.myseftcalendar.dialog.AddEditWeekLessonDialogFragment.WEEK_LESSON_ID;

public class WeekLessonDetailActivity extends AppCompatActivity implements View.OnClickListener,
        AddEditWeekLessonDialogFragment.AddEditWeekLessonDialogFragmentListener ,AddEditDetailCancelDialogFragment.AddEditDetailCancelDialogFragmentListener {

    private static final String TAG = WeekLessonDetailActivity.class.getSimpleName();
    private static final int ID_GROUP_SUBJECT = 1;

    private Context mContext;
    private Resources mResources;
    private DBHelper mDbHelper;
    private int mColorText;
    private int mColorBackground;
    private WeekLesson mWeekLesson = null;
    private Subject mSubject = null;

    private DayLessonAdapter mAdapter;

    //view
    private CoordinatorLayout mView_Coordinator;
    private TextView mView_SubjectName;
    private ImageView mView_SubjectArrow;
    private TextView mView_Weekday;
    private TextView mView_Repeat;
    private TextView mView_Day;
    private FloatingActionMenu mView_FABMenu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_week_lesson_detail);

        initData();
        initView();
    }

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

    private void initData() {
        mContext = this;
        mResources = mContext.getResources();
        mDbHelper = new DBHelper(mContext);

        Bundle bundle = getIntent().getBundleExtra(Constant.BUNDLE);
        int id = bundle.getInt(WEEK_LESSON_ID);
        try {
            mWeekLesson = mDbHelper.getWeekLesson(id);
            mSubject = mDbHelper.getSubject(mWeekLesson.getSubject_id(), null);
            mColorText = mSubject.getSubject_text_color();
            mColorBackground = mSubject.getSubject_background_color();
        } catch (NullObjectException e) {
            Log.d(TAG, e.toString());
            FunctionHelper.makeLToast(mContext, mResources.getString(R.string.error));
            this.finish();
        }
    }

    private void initView() {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(mContext, R.color.color_Actionbar)));
        }

        mView_Coordinator = findViewById(R.id.coordinator);
        mView_SubjectName = findViewById(R.id.week_lesson_detail_subject_name);
        mView_SubjectArrow = findViewById(R.id.arrow);
        mView_Weekday = findViewById(R.id.week_lesson_detail_weekday);
        mView_Repeat = findViewById(R.id.week_lesson_detail_repeat);
        mView_Day = findViewById(R.id.week_lesson_detail_day);
        mView_FABMenu = findViewById(R.id.fab_menu_1);
        FloatingActionButton addDayLesson = findViewById(R.id.fab_action_1);
        FloatingActionButton editWeekLesson = findViewById(R.id.fab_action_2);
        addDayLesson.setVisibility(View.VISIBLE);
        editWeekLesson.setVisibility(View.VISIBLE);
        addDayLesson.setLabelText(mResources.getString(R.string.add_day_lesson));
        editWeekLesson.setLabelText(mResources.getString(R.string.edit_week_lesson));
        editWeekLesson.setImageResource(R.drawable.ic_edit_white_24dp);

        RecyclerView mView_RecyclerView = findViewById(R.id.recycle_view);
        mView_RecyclerView.setNestedScrollingEnabled(false);
        mView_RecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new DayLessonAdapter(mContext, new ArrayList<DayLesson>(), mColorText, mColorBackground);
        @SuppressWarnings("unchecked") SwingBottomInAnimationAdapter animatorAdapter = new SwingBottomInAnimationAdapter(mAdapter, mView_RecyclerView);
        mView_RecyclerView.setAdapter(animatorAdapter);

        ItemTouchHelper.Callback callback = new ItemTouchHelperCallBackNoMove(mAdapter);
        ItemTouchHelper touchHelper = new ItemTouchHelper(callback);
        touchHelper.attachToRecyclerView(mView_RecyclerView);

        registerForContextMenu(mView_SubjectArrow);
        mView_SubjectArrow.setOnClickListener(this);
        mView_SubjectName.setOnClickListener(this);
        addDayLesson.setOnClickListener(this);
        editWeekLesson.setOnClickListener(this);
        setUpInfo();
    }

    private void setUpInfo() {
        mView_SubjectName.setText(mSubject.getSubject_name());
        mView_Weekday.setText(getWeekdayString());
        mView_Repeat.setText(getRepeatString());
        mView_Day.setText(getDayString());
    }

    public View getCoordinatorLayout() {
        return mView_Coordinator;
    }

    private String getRepeatString() {
        String repeat = "";
        try {
            repeat = mDbHelper.getRepeat(mWeekLesson.getRepeat_id(), null).getRepeat_name();
        } catch (NullObjectException e) {
            Log.d(TAG, e.toString());
        }
        return repeat;
    }

    private String getWeekdayString() {
        return DateTimeHelper.getDayShortNameString(mWeekLesson.getWeek_lesson_day_index());
    }

    private String getDayString() {
        return DateTimeHelper.getDayMonthYearString(mWeekLesson.getWeek_lesson_day_start()) + " - " +
                DateTimeHelper.getDayMonthYearString(mWeekLesson.getWeek_lesson_day_end());
    }

    //region menu
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case android.R.id.home:
                onBackPressed();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        //clear menu
        if (menu.size() != 0) {
            menu.clear();
        }

        int id_view = v.getId();

        switch (id_view) {
            case R.id.arrow:
                List<Subject> subjects = getSubjectList();
                if (subjects.size() == 0) {
                    FunctionHelper.makeSToast(mContext, mResources.getString(R.string.no_data_available));
                } else {
                    for (Subject s : subjects) {
                        //Add menu item with groupId
                        menu.add(ID_GROUP_SUBJECT, s.getSubject_id(), s.getSubject_id(), s.getSubject_name());
                    }
                    menu.setHeaderTitle(R.string.choose_a_subject);
                }
                break;
        }
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        int id_group = item.getGroupId();

        switch (id_group) {
            case ID_GROUP_SUBJECT:
                changeSubject(item.getItemId());
                break;
        }
        return super.onContextItemSelected(item);
    }
    //endregion

    private void changeSubject(int subject_id) {
        Subject subject = getSubject(subject_id);
        if (subject == null) return;
        if (mWeekLesson.getWeek_lesson_day_start() >= subject.getSubject_day_start()
                && mWeekLesson.getWeek_lesson_day_end() <= subject.getSubject_day_end()) {

            int oldID = mWeekLesson.getSubject_id();
            mWeekLesson.setSubject_id(subject.getSubject_id());
            DBHelper.DATABASE_CODE database_code = mDbHelper.updateWeekLessonSub(mWeekLesson);
            if (database_code != DBHelper.DATABASE_CODE.UPDATE_WEEK_LESSON_SUCCESS) {
                mWeekLesson.setSubject_id(oldID);
                FunctionHelper.makeSToast(mContext, mResources.getString(R.string.error_cant_change_subject));
                return;
            }

            mSubject = subject;
            onColorChange();
            mView_SubjectName.setText(subject.getSubject_name());
        } else {
            FunctionHelper.makeSToast(mContext, mResources.getString(R.string.error_cant_change_subject));
        }
    }

    private void onColorChange() {
        if (mColorText != mSubject.getSubject_text_color()) {
            mColorText = mSubject.getSubject_text_color();
            mAdapter.setTextColor(mColorText);
        }
        if (mColorBackground != mSubject.getSubject_background_color()) {
            mColorBackground = mSubject.getSubject_background_color();
            mAdapter.setBgColor(mColorBackground);
        }
    }

    private List<Subject> getSubjectList() {
        List<Subject> subjects = new ArrayList<>();
        try {
            subjects = mDbHelper.getSubjectList(true, null);
        } catch (NullObjectException e) {
            Log.d(TAG, e.toString());
        }
        return subjects;
    }

    private Subject getSubject(int subject_id) {
        try {
            return mDbHelper.getSubject(subject_id, null);
        } catch (NullObjectException e) {
            Log.d(TAG, e.toString());
            return null;

        }
    }

    private void reLoadData() {
        if (mWeekLesson == null) {
            FunctionHelper.makeLToast(mContext,mResources.getString(R.string.error));
            this.finish();
        }

        int id = mWeekLesson.getWeek_lesson_id();
        try {
            mWeekLesson = mDbHelper.getWeekLesson(id);
            mSubject = mDbHelper.getSubject(mWeekLesson.getSubject_id(), null);
            onColorChange();
            setUpInfo();
            List<DayLesson> dayLessons = mDbHelper.getDayLessonList(mWeekLesson.getWeek_lesson_id(), null,false);
            mAdapter.reload(dayLessons);
        } catch (NullObjectException e) {
            Log.d(TAG, e.toString());
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.arrow:
                mView_SubjectArrow.showContextMenu();
                break;

            case R.id.week_lesson_detail_subject_name:
                mView_SubjectArrow.showContextMenu();
                break;

            case R.id.fab_action_1:
                if (mView_FABMenu.isOpened()) {
                    mView_FABMenu.close(true);
                    AddEditWeekLessonDialogFragment dialogFragment = new AddEditWeekLessonDialogFragment();
                    dialogFragment.show(((WeekLessonDetailActivity) mContext).getSupportFragmentManager(), "");

                    Bundle bundle = new Bundle();
                    bundle.putInt(WEEK_LESSON_DIALOG_MODE, DAY_LESSON_DIALOG_ADD_MODE);
                    bundle.putInt(WEEK_LESSON_ID, mWeekLesson.getWeek_lesson_id());
                    dialogFragment.setArguments(bundle);
                }
                break;

            case R.id.fab_action_2:
                if (mView_FABMenu.isOpened()) {
                    mView_FABMenu.close(true);
                    AddEditWeekLessonDialogFragment dialogFragment = new AddEditWeekLessonDialogFragment();
                    dialogFragment.show(((WeekLessonDetailActivity) mContext).getSupportFragmentManager(), "");
                    Bundle bundle = new Bundle();
                    bundle.putInt(WEEK_LESSON_DIALOG_MODE, WEEK_LESSON_DIALOG_EDIT_MODE);
                    WeekLessonDialogItem item = new WeekLessonDialogItem();
                    item.setWeekLesson(mWeekLesson);
                    item.setOld(true);
                    bundle.putParcelable(WEEK_LESSON_DIALOG_ITEM, item);
                    bundle.putInt(WEEK_LESSON_DIALOG_ITEM_POS, Constant.INT_NONE_VALUE);
                    dialogFragment.setArguments(bundle);
                }
                break;
        }
    }

    @Override
    public void onAddWeekLesson(WeekLessonDialogItem weekLessonDialogItem) {

    }

    @Override
    public void onEditWeekLesson(WeekLessonDialogItem weekLessonDialogItem, int pos) {
        WeekLesson weekLesson = weekLessonDialogItem.getWeekLesson();
        DBHelper.DATABASE_CODE database_code = mDbHelper.updateWeekLesson(weekLesson);
        if (database_code != DBHelper.DATABASE_CODE.UPDATE_WEEK_LESSON_SUCCESS) {
            Log.d(TAG, new DBStringHelper(mContext).getDBString(database_code));
            FunctionHelper.makeLToast(mContext, new DBStringHelper(mContext).getDBString(database_code));
            return;
        }
        reLoadData();
    }

    @Override
    public void onAddDayLesson(DayLesson dayLesson) {
        DBHelper.DATABASE_CODE database_code = mDbHelper.insertDayLesson(dayLesson);
        if (database_code != DBHelper.DATABASE_CODE.INSERT_DAY_LESSON_SUCCESS) {
            Log.d(TAG, new DBStringHelper(mContext).getDBString(database_code));
            FunctionHelper.makeLToast(mContext, new DBStringHelper(mContext).getDBString(database_code));
            return;
        }
        mAdapter.insertNewItem(dayLesson);
    }

    @Override
    public void onEditDayLesson(DayLesson dayLesson, int pos) {
        if (pos >= 0 && pos < mAdapter.getItemCount()) {
            DBHelper.DATABASE_CODE database_code = mDbHelper.updateDayLesson(dayLesson);
            if (database_code != DBHelper.DATABASE_CODE.UPDATE_DAY_LESSON_SUCCESS) {
                Log.d(TAG, new DBStringHelper(mContext).getDBString(database_code));
                FunctionHelper.makeLToast(mContext, new DBStringHelper(mContext).getDBString(database_code));
                return;
            }
            mAdapter.notifyItemChanged(dayLesson, pos);
        }
    }

    @Override
    public void onDoCancel(DayLesson dayLesson, int pos) {
        mAdapter.notifyItemChanged(dayLesson, pos);
    }
}