package net.micode.notes.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.SearchManager;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.style.BackgroundColorSpan;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.model.WorkingNote;
import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.ResourceParser;

import java.util.HashSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TrashNoteActivity extends Activity {

    private class HeadViewHolder {
        public TextView tvModified;

        public ImageView ivAlertIcon;

        public TextView tvAlertDate;
        public ImageView ibSetBgColor;
    }

    private static final String TAG = "TrashNoteActivity";

    private TrashNoteActivity.HeadViewHolder mNoteHeaderHolder;
    private View mHeadViewPanel;
    private LinearLayout mEditTextList;
    private EditText mNoteEditor;
    private View mNoteEditorPanel;
    private SharedPreferences mSharedPrefs;
    private View mFontSizeSelector;
    private static final String PREFERENCE_FONT_SIZE = "pref_font_size";
    private int mFontSizeId;
    private Pattern mPattern;

    private WorkingNote mWorkingNote;

    private String mUserQuery;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.note_edit);

        if (savedInstanceState == null && !initActivityState(getIntent())) {
            finish();
            return;
        }

        initResources();
    }

    private boolean initActivityState(Intent intent) {
        /**
         * If the user specified the {@link Intent#ACTION_VIEW} but not provided with id,
         * then jump to the NotesListActivity
         */
        mWorkingNote = null;
        if (TextUtils.equals(Intent.ACTION_VIEW, intent.getAction())) {
            long noteId = intent.getLongExtra(Intent.EXTRA_UID, 0);
            mUserQuery = "";

            /**
             * Starting from the searched result
             */
            if (intent.hasExtra(SearchManager.EXTRA_DATA_KEY)) {
                noteId = Long.parseLong(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
                mUserQuery = intent.getStringExtra(SearchManager.USER_QUERY);
            }

            System.out.println("--------->>>>"+noteId);

            if (!DataUtils.visibleInTrashNoteDatabase(getContentResolver(), noteId, Notes.TYPE_NOTE)) {
                Intent jump = new Intent(this, NotesListActivity.class);
                startActivity(jump);
                showToast(R.string.error_note_not_exist);
                finish();
                return false;
            } else {
                mWorkingNote = WorkingNote.load(this, noteId);
                if (mWorkingNote == null) {
                    Log.e(TAG, "load note failed with note id" + noteId);
                    finish();
                    return false;
                }
            }

            getWindow().setSoftInputMode(
                    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        } else {
            Log.e(TAG, "Intent not specified action, should not support");
            finish();
            return false;
        }
        return true;
    }

    private void initResources() {
        mHeadViewPanel = findViewById(R.id.note_title);
        mNoteHeaderHolder = new TrashNoteActivity.HeadViewHolder();
        mNoteHeaderHolder.tvModified = (TextView) findViewById(R.id.tv_modified_date);
        mNoteHeaderHolder.ivAlertIcon = (ImageView) findViewById(R.id.iv_alert_icon);
        mNoteHeaderHolder.tvAlertDate = (TextView) findViewById(R.id.tv_alert_date);
        mNoteHeaderHolder.ibSetBgColor = (ImageButton) findViewById(R.id.color_selector);
        mNoteHeaderHolder.tvAlertDate.setVisibility(View.GONE);
        mNoteHeaderHolder.ivAlertIcon.setVisibility(View.GONE);
        mNoteHeaderHolder.ibSetBgColor.setVisibility(View.GONE);
        mNoteEditor = (EditText) findViewById(R.id.note_edit_view);
        mNoteEditorPanel = findViewById(R.id.sv_note_edit);
        mFontSizeSelector = findViewById(R.id.font_size_selector);
        mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
        mFontSizeId = mSharedPrefs.getInt(PREFERENCE_FONT_SIZE, ResourceParser.BG_DEFAULT_FONT_SIZE);
        /**
         * HACKME: Fix bug of store the resource id in shared preference.
         * The id may larger than the length of resources, in this case,
         * return the {@link ResourceParser#BG_DEFAULT_FONT_SIZE}
         */
        if(mFontSizeId >= ResourceParser.TextAppearanceResources.getResourcesSize()) {
            mFontSizeId = ResourceParser.BG_DEFAULT_FONT_SIZE;
        }
        mEditTextList = (LinearLayout) findViewById(R.id.note_edit_list);
    }

    protected void onResume() {
        super.onResume();
        initNoteScreen();
        long time = System.currentTimeMillis();
    }

    private void initNoteScreen() {
        mNoteEditor.setTextAppearance(this, ResourceParser.TextAppearanceResources
                .getTexAppearanceResource(mFontSizeId));
        mNoteEditor.setText(getHighlightQueryResult(mWorkingNote.getContent(), mUserQuery));
        mNoteEditor.setSelection(mNoteEditor.getText().length());
        mHeadViewPanel.setBackgroundResource(mWorkingNote.getTitleBgResId());
        mNoteEditorPanel.setBackgroundResource(mWorkingNote.getBgColorResId());
        mNoteHeaderHolder.tvModified.setText(DateUtils.formatDateTime(this,
                mWorkingNote.getModifiedDate(), DateUtils.FORMAT_SHOW_DATE
                        | DateUtils.FORMAT_NUMERIC_DATE | DateUtils.FORMAT_SHOW_TIME
                        | DateUtils.FORMAT_SHOW_YEAR));
    }

    private Spannable getHighlightQueryResult(String fullText, String userQuery) {
        SpannableString spannable = new SpannableString(fullText == null ? "" : fullText);
        if (!TextUtils.isEmpty(userQuery)) {
            mPattern = Pattern.compile(userQuery);
            Matcher m = mPattern.matcher(fullText);
            int start = 0;
            while (m.find(start)) {
                spannable.setSpan(
                        new BackgroundColorSpan(this.getResources().getColor(
                                R.color.user_query_highlight)), m.start(), m.end(),
                        Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                start = m.end();
            }
        }
        return spannable;
    }

    public boolean onPrepareOptionsMenu(Menu menu) {
        if (isFinishing()) {
            return true;
        }
        menu.clear();
        getMenuInflater().inflate(R.menu.trash_note, menu);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_go_back:
                if(DataUtils.visibleInTrashNoteDatabase(getContentResolver(),
                        mWorkingNote.getNoteOriginId(), Notes.TYPE_NOTE)){
                    moveNoteToSrcFolder(getContentResolver(),mWorkingNote.getNoteId());
                } else {
                    moveNoteToSrcFolder(getContentResolver(),mWorkingNote.getNoteId());
                }
                onBackPressed();
                break;
            case R.id.menu_delete:
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle(getString(R.string.alert_title_delete));
                builder.setIcon(android.R.drawable.ic_dialog_alert);
                builder.setMessage(getString(R.string.alert_message_delete_note));
                builder.setPositiveButton(android.R.string.ok,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                deleteTrashNote();
                                finish();
                                onBackPressed();
                            }
                        });
                builder.setNegativeButton(android.R.string.cancel, null);
                builder.show();
                break;
            default:
                break;
        }
        return true;
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    private void deleteTrashNote() {
        if (mWorkingNote.existInDatabase()) {
            HashSet<Long> ids = new HashSet<Long>();
            long id = mWorkingNote.getNoteId();
            if (id != Notes.ID_ROOT_FOLDER) {
                ids.add(id);
            } else {
                Log.d(TAG, "Wrong note id, should not happen");
            }

            if (!DataUtils.batchDeleteNotes(getContentResolver(), ids)) {
                Log.e(TAG, "Delete Note error");
            }
        }
        mWorkingNote.markDeleted(true);
    }

    private void moveNoteToSrcFolder(ContentResolver resolver, long id) {
        ContentValues values = new ContentValues();
        if(DataUtils.visibleInTrashNoteDatabase(getContentResolver(),
                mWorkingNote.getNoteOriginId(), Notes.TYPE_NOTE)){
            values.put(Notes.NoteColumns.PARENT_ID, mWorkingNote.getNoteOriginId());
        } else {
            values.put(Notes.NoteColumns.PARENT_ID, Notes.ID_ROOT_FOLDER);
        }
        values.put(Notes.NoteColumns.ORIGIN_PARENT_ID, Notes.ID_ROOT_FOLDER);
        values.put(Notes.NoteColumns.LOCAL_MODIFIED, 1);
        resolver.update(ContentUris.withAppendedId(Notes.CONTENT_NOTE_URI, id), values, null, null);
    }

    private void showToast(int resId) {
        showToast(resId, Toast.LENGTH_SHORT);
    }

    private void showToast(int resId, int duration) {
        Toast.makeText(this, resId, duration).show();
    }
}