/*
 * 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.model;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;

import net.micode.notes.data.Notes;

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

/**
 * 标签数据模型类
 * 表示笔记标签的核心数据结构和操作方法
 * 提供标签的增删改查、与笔记的关联等功能
 */
public class Tag {
    // 日志标签
    private static final String TAG = "Tag";

    // 标签查询投影数组
    public static final String[] TAG_PROJECTION = new String[] {
        "id",           // 标签ID
        "name",         // 标签名称
        "color",        // 标签颜色
        "created_date"  // 创建日期
    };

    // 列索引常量定义
    public static final int TAG_ID_COLUMN = 0;              // ID列索引
    public static final int TAG_NAME_COLUMN = 1;            // 名称列索引
    public static final int TAG_COLOR_COLUMN = 2;           // 颜色列索引
    public static final int TAG_CREATED_DATE_COLUMN = 3;    // 创建日期列索引

    // 标签颜色常量定义
    public static final int COLOR_BLUE = 0;     // 蓝色
    public static final int COLOR_GREEN = 1;    // 绿色
    public static final int COLOR_ORANGE = 2;   // 橙色
    public static final int COLOR_RED = 3;      // 红色
    public static final int COLOR_PURPLE = 4;   // 紫色
    public static final int COLOR_GRAY = 5;     // 灰色

    // 标签属性
    private long mId;           // 标签ID
    private String mName;       // 标签名称
    private int mColor;         // 标签颜色
    private long mCreatedDate;  // 创建日期
    private Context mContext;   // 上下文对象
    
    /**
     * 默认构造方法
     * 创建一个新的标签，使用默认值
     * @param context 上下文对象
     */
    public Tag(Context context) {
        mContext = context;
        mId = -1;                                   // 新标签ID为-1
        mName = "";                                 // 默认名称为空
        mColor = COLOR_BLUE;                        // 默认颜色为蓝色
        mCreatedDate = System.currentTimeMillis();  // 当前时间为创建时间
    }

    /**
     * 完整参数构造方法
     * 使用指定的参数创建标签
     * @param context 上下文对象
     * @param id 标签ID
     * @param name 标签名称
     * @param color 标签颜色
     * @param createdDate 创建日期
     */
    public Tag(Context context, long id, String name, int color, long createdDate) {
        mContext = context;
        mId = id;
        mName = name;
        mColor = color;
        mCreatedDate = createdDate;
    }

    /**
     * 从游标创建标签对象
     * @param context 上下文对象
     * @param cursor 数据库游标
     * @return 标签对象
     */
    public static Tag createFromCursor(Context context, Cursor cursor) {
        return new Tag(
            context,
            cursor.getLong(TAG_ID_COLUMN),
            cursor.getString(TAG_NAME_COLUMN),
            cursor.getInt(TAG_COLOR_COLUMN),
            cursor.getLong(TAG_CREATED_DATE_COLUMN)
        );
    }

    /**
     * 保存标签到数据库
     * 如果是新标签则插入，如果是已存在标签则更新
     * @return 保存成功返回标签ID，失败返回-1
     */
    public long save() {
        ContentValues values = new ContentValues();
        values.put("name", mName);
        values.put("color", mColor);
        values.put("created_date", mCreatedDate);

        if (mId == -1) {
            // 插入新标签
            Uri uri = mContext.getContentResolver().insert(
                Uri.parse("content://micode_notes/tag"), values);
            if (uri != null) {
                mId = Long.parseLong(uri.getLastPathSegment());
                return mId;
            }
        } else {
            // 更新已存在的标签
            int count = mContext.getContentResolver().update(
                Uri.parse("content://micode_notes/tag/" + mId),
                values, null, null);
            return count > 0 ? mId : -1;
        }
        return -1;
    }
    
    public boolean delete() {
        if (mId == -1) return false;
        
        int count = mContext.getContentResolver().delete(
            Uri.parse("content://micode_notes/tag/" + mId), null, null);
        return count > 0;
    }
    
    public static List<Tag> getAllTags(Context context) {
        List<Tag> tags = new ArrayList<>();
        Cursor cursor = context.getContentResolver().query(
            Uri.parse("content://micode_notes/tag"),
            TAG_PROJECTION, null, null, "name ASC");
            
        if (cursor != null) {
            while (cursor.moveToNext()) {
                tags.add(createFromCursor(context, cursor));
            }
            cursor.close();
        }
        return tags;
    }
    
    public static List<Tag> getTagsForNote(Context context, long noteId) {
        List<Tag> tags = new ArrayList<>();
        Cursor cursor = context.getContentResolver().query(
            Uri.parse("content://micode_notes/note_tag"),
            new String[]{"tag_id"}, 
            "note_id=?", 
            new String[]{String.valueOf(noteId)}, 
            null);
            
        if (cursor != null) {
            while (cursor.moveToNext()) {
                long tagId = cursor.getLong(0);
                Tag tag = getTagById(context, tagId);
                if (tag != null) {
                    tags.add(tag);
                }
            }
            cursor.close();
        }
        return tags;
    }
    
    public static Tag getTagById(Context context, long tagId) {
        Cursor cursor = context.getContentResolver().query(
            Uri.parse("content://micode_notes/tag"),
            TAG_PROJECTION, 
            "id=?", 
            new String[]{String.valueOf(tagId)}, 
            null);
            
        if (cursor != null && cursor.moveToFirst()) {
            Tag tag = createFromCursor(context, cursor);
            cursor.close();
            return tag;
        }
        if (cursor != null) cursor.close();
        return null;
    }
    
    public void addToNote(long noteId) {
        if (mId == -1) return;
        
        ContentValues values = new ContentValues();
        values.put("note_id", noteId);
        values.put("tag_id", mId);
        
        mContext.getContentResolver().insert(
            Uri.parse("content://micode_notes/note_tag"), values);
    }
    
    public void removeFromNote(long noteId) {
        if (mId == -1) return;
        
        mContext.getContentResolver().delete(
            Uri.parse("content://micode_notes/note_tag"),
            "note_id=? AND tag_id=?",
            new String[]{String.valueOf(noteId), String.valueOf(mId)});
    }
    
    // Getters and Setters
    public long getId() { return mId; }
    public String getName() { return mName; }
    public void setName(String name) { mName = name; }
    public int getColor() { return mColor; }
    public void setColor(int color) { mColor = color; }
    public long getCreatedDate() { return mCreatedDate; }
    
    @Override
    public String toString() {
        return mName;
    }
    
    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        Tag tag = (Tag) obj;
        return mId == tag.mId;
    }
    
    @Override
    public int hashCode() {
        return (int) (mId ^ (mId >>> 32));
    }
}
