/*
 * 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.AlertDialog;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

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

public class TrashActivity extends Activity implements OnClickListener {
    private static final String TAG = "TrashActivity";
    
    private static final int TRASH_LIST_QUERY_TOKEN = 0;
    
    private Button mReturnButton;
    private Button mCleanAllButton;
    private ListView mTrashListView;
    private NotesListAdapter mTrashListAdapter;
    private ContentResolver mContentResolver;
    private BackgroundQueryHandler mBackgroundQueryHandler;

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

    @Override
    protected void onStart() {
        super.onStart();
        startAsyncTrashListQuery();
    }

    private void initResources() {
        mContentResolver = this.getContentResolver();
        mBackgroundQueryHandler = new BackgroundQueryHandler(mContentResolver);
        
        mReturnButton = (Button) findViewById(R.id.btn_return);
        if (mReturnButton != null) {
            mReturnButton.setOnClickListener(this);
        }
        
        mCleanAllButton = (Button) findViewById(R.id.btn_clean_all);
        if (mCleanAllButton != null) {
            mCleanAllButton.setOnClickListener(this);
        }
        
        mTrashListView = (ListView) findViewById(R.id.trash_list);
        if (mTrashListView != null) {
            mTrashListAdapter = new NotesListAdapter(this);
            mTrashListView.setAdapter(mTrashListAdapter);
            mTrashListView.setOnItemClickListener(new OnTrashItemClickListener());
        }
    }

    private void startAsyncTrashListQuery() {
        mBackgroundQueryHandler.startQuery(TRASH_LIST_QUERY_TOKEN, null,
                Notes.CONTENT_TRASH_URI, NoteItemData.PROJECTION, null, null,
                NoteColumns.MODIFIED_DATE + " DESC");
    }

    private final class BackgroundQueryHandler extends AsyncQueryHandler {
        public BackgroundQueryHandler(ContentResolver contentResolver) {
            super(contentResolver);
        }

        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            switch (token) {
                case TRASH_LIST_QUERY_TOKEN:
                    mTrashListAdapter.changeCursor(cursor);
                    break;
                default:
                    break;
            }
        }
    }

    private class OnTrashItemClickListener implements OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (view instanceof NotesListItem) {
                NoteItemData item = ((NotesListItem) view).getItemData();
                showTrashItemDialog(item);
            }
        }
    }

    private void showTrashItemDialog(final NoteItemData item) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(item.getSnippet());
        builder.setItems(new String[] {
                getString(R.string.menu_delete),
                getString(R.string.button_recovery)
        }, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0: // Delete - 彻底删除
                        permanentlyDeleteNote(item.getId());
                        break;
                    case 1: // Recovery - 恢复
                        recoverNote(item.getId());
                        break;
                }
            }
        });
        builder.show();
    }

    private void permanentlyDeleteNote(long noteId) {
        if (DataUtils.permanentlyDeleteFromTrash(mContentResolver, noteId, this)) {
            Toast.makeText(this, getString(R.string.menu_delete) + " " + getString(R.string.menu_success), 
                    Toast.LENGTH_SHORT).show();
            startAsyncTrashListQuery(); // Refresh list
        } else {
            Toast.makeText(this, getString(R.string.menu_delete) + " " + getString(R.string.failed_sdcard_export), 
                    Toast.LENGTH_SHORT).show();
        }
    }

    private void recoverNote(long noteId) {
        if (DataUtils.restoreNoteFromTrash(mContentResolver, noteId, this)) {
            Toast.makeText(this, getString(R.string.button_recovery) + " " + getString(R.string.menu_success), 
                    Toast.LENGTH_SHORT).show();
            startAsyncTrashListQuery(); // Refresh list
        } else {
            Toast.makeText(this, getString(R.string.button_recovery) + " " + getString(R.string.failed_sdcard_export), 
                    Toast.LENGTH_SHORT).show();
        }
    }

    private void showClearAllTrashDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.button_clean_all));
        builder.setMessage(getString(R.string.alert_message_clear_all_trash));
        builder.setPositiveButton(android.R.string.ok,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        clearAllTrash();
                    }
                });
        builder.setNegativeButton(android.R.string.cancel, null);
        builder.show();
    }

    private void clearAllTrash() {
        if (DataUtils.clearAllTrash(mContentResolver, this)) {
            Toast.makeText(this, getString(R.string.button_clean_all) + " " + getString(R.string.menu_success), 
                    Toast.LENGTH_SHORT).show();
            startAsyncTrashListQuery(); // Refresh list to clear UI
        } else {
            Toast.makeText(this, getString(R.string.button_clean_all) + " " + getString(R.string.failed_sdcard_export), 
                    Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_return:
                finish();
                break;
            case R.id.btn_clean_all:
                showClearAllTrashDialog();
                break;
            default:
                break;
        }
    }
}