/*
 * 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.DialogInterface;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import net.micode.notes.R;
import net.micode.notes.model.Tag;
import net.micode.notes.tool.ThemeManager;

import java.util.List;

/**
 * 标签管理Activity
 * 负责标签的创建、编辑、删除和显示功能
 */
public class TagManagerActivity extends Activity {
    // 标签列表视图
    private ListView mTagListView;
    // 标签适配器
    private TagAdapter mTagAdapter;
    // 标签数据列表
    private List<Tag> mTags;

    /**
     * Activity创建时的回调方法
     * 初始化界面和数据
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 应用主题
        ThemeManager.applyTheme(this);
        // 设置布局
        setContentView(R.layout.tag_manager);

        // 初始化视图
        initViews();
        // 加载标签数据
        loadTags();
    }

    /**
     * 初始化视图组件
     * 设置列表视图和监听器
     */
    private void initViews() {
        mTagListView = findViewById(R.id.tag_list);
        mTagAdapter = new TagAdapter();
        mTagListView.setAdapter(mTagAdapter);

        // 注册上下文菜单
        registerForContextMenu(mTagListView);

        // 设置列表项点击监听器
        mTagListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // 点击列表项时编辑标签
                editTag(mTags.get(position));
            }
        });
    }

    /**
     * 加载所有标签数据
     * 从数据库获取标签并刷新列表
     */
    private void loadTags() {
        mTags = Tag.getAllTags(this);
        mTagAdapter.notifyDataSetChanged();
    }
    
    /**
     * 创建选项菜单
     * 加载标签管理菜单
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.tag_manager, menu);
        return true;
    }

    /**
     * 处理选项菜单项点击事件
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == R.id.menu_add_tag) {
            // 添加新标签
            addNewTag();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 创建上下文菜单
     * 为列表项提供编辑和删除选项
     */
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        getMenuInflater().inflate(R.menu.tag_context, menu);
    }

    /**
     * 处理上下文菜单项点击事件
     */
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info =
            (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        Tag tag = mTags.get(info.position);

        int itemId = item.getItemId();
        if (itemId == R.id.menu_edit_tag) {
            // 编辑标签
            editTag(tag);
            return true;
        } else if (itemId == R.id.menu_delete_tag) {
            // 删除标签
            deleteTag(tag);
            return true;
        }
        return super.onContextItemSelected(item);
    }

    /**
     * 添加新标签
     * 显示标签编辑对话框
     */
    private void addNewTag() {
        showTagDialog(null);
    }

    /**
     * 编辑现有标签
     * @param tag 要编辑的标签对象
     */
    private void editTag(Tag tag) {
        showTagDialog(tag);
    }
    
    private void showTagDialog(final Tag tag) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_tag_edit, null);
        
        final EditText nameEdit = dialogView.findViewById(R.id.tag_name_edit);
        final View[] colorViews = {
            dialogView.findViewById(R.id.color_blue),
            dialogView.findViewById(R.id.color_green),
            dialogView.findViewById(R.id.color_orange),
            dialogView.findViewById(R.id.color_red),
            dialogView.findViewById(R.id.color_purple),
            dialogView.findViewById(R.id.color_gray)
        };
        
        final int[] selectedColor = {Tag.COLOR_BLUE};
        
        if (tag != null) {
            nameEdit.setText(tag.getName());
            selectedColor[0] = tag.getColor();
            builder.setTitle(R.string.edit_tag);
        } else {
            builder.setTitle(R.string.add_tag);
        }
        
        // Set up color selection
        for (int i = 0; i < colorViews.length; i++) {
            final int colorIndex = i;
            colorViews[i].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    selectedColor[0] = colorIndex;
                    updateColorSelection(colorViews, colorIndex);
                }
            });
        }
        
        updateColorSelection(colorViews, selectedColor[0]);
        
        builder.setView(dialogView)
               .setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
                   @Override
                   public void onClick(DialogInterface dialog, int which) {
                       String name = nameEdit.getText().toString().trim();
                       if (name.isEmpty()) {
                           Toast.makeText(TagManagerActivity.this, 
                               R.string.tag_name_empty, Toast.LENGTH_SHORT).show();
                           return;
                       }
                       
                       if (tag != null) {
                           // Edit existing tag
                           tag.setName(name);
                           tag.setColor(selectedColor[0]);
                           tag.save();
                       } else {
                           // Create new tag
                           Tag newTag = new Tag(TagManagerActivity.this);
                           newTag.setName(name);
                           newTag.setColor(selectedColor[0]);
                           newTag.save();
                       }
                       
                       loadTags();
                   }
               })
               .setNegativeButton(R.string.cancel, null)
               .show();
    }
    
    private void updateColorSelection(View[] colorViews, int selectedIndex) {
        for (int i = 0; i < colorViews.length; i++) {
            colorViews[i].setSelected(i == selectedIndex);
        }
    }
    
    private void deleteTag(final Tag tag) {
        new AlertDialog.Builder(this)
            .setTitle(R.string.delete_tag)
            .setMessage(getString(R.string.delete_tag_confirm, tag.getName()))
            .setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    tag.delete();
                    loadTags();
                    Toast.makeText(TagManagerActivity.this, 
                        R.string.tag_deleted, Toast.LENGTH_SHORT).show();
                }
            })
            .setNegativeButton(R.string.cancel, null)
            .show();
    }
    
    private class TagAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return mTags != null ? mTags.size() : 0;
        }
        
        @Override
        public Object getItem(int position) {
            return mTags.get(position);
        }
        
        @Override
        public long getItemId(int position) {
            return mTags.get(position).getId();
        }
        
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(TagManagerActivity.this)
                    .inflate(R.layout.tag_list_item, parent, false);
            }
            
            Tag tag = mTags.get(position);
            
            TextView nameView = convertView.findViewById(R.id.tag_name);
            View colorView = convertView.findViewById(R.id.tag_color);
            
            nameView.setText(tag.getName());
            colorView.setBackgroundColor(ThemeManager.getTagColor(TagManagerActivity.this, tag.getColor()));
            
            return convertView;
        }
    }
}
