/*
 * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.micode.notes.ui;

import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;

public class SearchActivity extends Activity implements View.OnClickListener {
    private static final String[] PROJECTION = new String[] {
            NoteColumns.ID,
            NoteColumns.SNIPPET,
            NoteColumns.MODIFIED_DATE
    };

    private ListView mListView;
    private EditText mSearchEditText;
    private ImageButton mSearchButton;
    private SearchAdapter mAdapter;
    private InputMethodManager mInputMethodManager;

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

        mListView = findViewById(R.id.search_list);
        mSearchEditText = findViewById(R.id.search_edit);
        mSearchButton = findViewById(R.id.search_button);
        mSearchButton.setOnClickListener(this);
        
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                openNoteById(id);
            }
        });

        mInputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        mAdapter = new SearchAdapter(this, null);
        mListView.setAdapter(mAdapter);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.search_button) {
            String searchText = mSearchEditText.getText().toString();
            if (!TextUtils.isEmpty(searchText)) {
                performSearch(searchText);
                // 隐藏键盘
                mInputMethodManager.hideSoftInputFromWindow(mSearchEditText.getWindowToken(), 0);
            } else {
                Toast.makeText(this, R.string.search_hint, Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void performSearch(String query) {
        String selection = NoteColumns.SNIPPET + " LIKE ? AND " + 
                           NoteColumns.PARENT_ID + "<>" + Notes.ID_TRASH_FOLER + " AND " +
                           NoteColumns.TYPE + "=" + Notes.TYPE_NOTE;
        String[] selectionArgs = new String[] {"%" + query + "%"};
        
        Cursor cursor = getContentResolver().query(
                Notes.CONTENT_NOTE_URI, 
                PROJECTION, 
                selection, 
                selectionArgs, 
                NoteColumns.MODIFIED_DATE + " DESC"
        );
        
        if (cursor != null && cursor.getCount() > 0) {
            mAdapter.changeCursor(cursor);
            mListView.setVisibility(View.VISIBLE);
        } else {
            if (cursor != null) {
                cursor.close();
            }
            mAdapter.changeCursor(null);
            Toast.makeText(this, R.string.notelist_string_no_search_result, Toast.LENGTH_SHORT).show();
        }
    }

    private void openNoteById(long id) {
        Intent intent = new Intent(this, NoteEditActivity.class);
        intent.setAction(Intent.ACTION_VIEW);
        intent.putExtra(Intent.EXTRA_UID, id);
        startActivity(intent);
    }

    private class SearchAdapter extends CursorAdapter {
        public SearchAdapter(Context context, Cursor c) {
            super(context, c, 0);
        }

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            return LayoutInflater.from(context).inflate(R.layout.note_item, parent, false);
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            TextView titleView = view.findViewById(R.id.tv_title);
            String snippet = cursor.getString(cursor.getColumnIndexOrThrow(NoteColumns.SNIPPET));
            // 删除所有换行符和前后空格，方便显示
            snippet = snippet.replace('\n', ' ').trim();
            titleView.setText(snippet);

            TextView timeView = view.findViewById(R.id.tv_time);
            long modifiedDate = cursor.getLong(cursor.getColumnIndexOrThrow(NoteColumns.MODIFIED_DATE));
            timeView.setText(android.text.format.DateUtils.getRelativeTimeSpanString(modifiedDate));
        }
    }
} 