import json
from datetime import datetime
import pytz
import time
import gradio as gr

js = """
function createGradioAnimation() {
    var container = document.createElement('div');
    container.id = 'gradio-animation';
    container.style.fontSize = '2em';
    container.style.fontWeight = 'bold';
    container.style.textAlign = 'center';
    container.style.marginBottom = '20px';

    var text = 'Welcome to Code Tools!';
    for (var i = 0; i < text.length; i++) {
        (function(i){
            setTimeout(function(){
                var letter = document.createElement('span');
                letter.style.opacity = '0';
                letter.style.transition = 'opacity 0.5s';
                letter.innerText = text[i];

                container.appendChild(letter);

                setTimeout(function() {
                    letter.style.opacity = '1';
                }, 50);
            }, i * 250);
        })(i);
    }

    var gradioContainer = document.querySelector('.gradio-container');
    gradioContainer.insertBefore(container, gradioContainer.firstChild);

    return 'Animation created';
}
"""


def json_format(data):
    try:
        data = json.loads(data)
        return data
    except:
        raise gr.Error("Json数据格式不正确!")


def html_format(data):
    return data


def md_format(data):
    return data


# 获取当前 Unix 时间戳
def get_current_timestamp(precision):
    timestamp = int(time.time() * 1000) if precision == "ms" else int(time.time())
    return str(timestamp)


# 时间戳转换为日期
def timestamp_to_date(input_time, target_timezone, precision):
    try:
        if precision == "ms":
            input_time = int(input_time) / 1000  # 毫秒转为秒
        else:
            input_time = int(input_time)  # 秒级时间戳

        # 将输入的 Unix 时间戳转换为 UTC 时间
        utc_time = datetime.utcfromtimestamp(input_time).replace(tzinfo=pytz.utc)

        # 获取目标时区
        target_tz = pytz.timezone(target_timezone)

        # 转换到目标时区
        target_time = utc_time.astimezone(target_tz)

        # 返回格式化后的时间
        return target_time.strftime("%Y-%m-%d %H:%M:%S")
    except Exception as e:
        return f"error: {e}"


# 日期转换为时间戳
def date_to_timestamp(input_date, target_timezone):
    try:
        # 解析日期输入为 datetime 对象
        target_tz = pytz.timezone(target_timezone)
        target_time = datetime.fromisoformat(input_date).astimezone(target_tz)

        # 转换为 UTC 时间戳
        timestamp = int(target_time.astimezone(pytz.utc).timestamp())

        return str(timestamp)
    except Exception as e:
        return f"error: {e}"


# 获取所有时区列表
timezones = pytz.all_timezones

with gr.Blocks(title='Gradio-Tools', theme=gr.themes.Ocean(), js=js) as demo:
    with gr.Tabs():
        with gr.Tab("Json Format"):
            with gr.Row():
                json_input = gr.Textbox(label="Json Data", interactive=True, placeholder="{}", lines=50)
                json_output = gr.Json(label="Json Format")

        json_input.change(fn=json_format, inputs=json_input, outputs=json_output)

        with gr.Tab("Timestamp Conversion"):
            with gr.Row():
                # 时间戳输入框,显示当前时间戳
                timestamp_input = gr.Textbox(
                    label="Timestamp (s/ms)",
                    value=get_current_timestamp("s"),  # 默认显示当前秒级时间戳
                    interactive=True,  # 可编辑
                    elem_id="timestamp_input",
                    placeholder="Please enter a timestamp"
                )

                # 选择精度(秒或毫秒)
                precision = gr.Dropdown(
                    ["s", "ms"],
                    label="Timestamp accuracy",
                    value="s",  # 默认秒
                    elem_id="precision"
                )

                target_timezone = gr.Dropdown(
                    timezones,
                    label="Target time zone",
                    value="Asia/Shanghai",  # 默认设置为北京时间
                    elem_id="target_timezone"
                )

            with gr.Row():
                # 日期输入框,用户输入日期
                date_input = gr.Textbox(
                    label="Date Input (ISO 8601)",
                    placeholder="For example:2025-01-01 12:34:56",
                    elem_id="date_input"
                )

                output = gr.Textbox(label="Conversion results", elem_id="output")

            with gr.Row():
                # 时间戳转日期按钮
                timestamp_to_date_btn = gr.Button("Timestamp to date", elem_id="timestamp_to_date_btn")

                # 日期转时间戳按钮
                date_to_timestamp_btn = gr.Button("Date to timestamp", elem_id="date_to_timestamp_btn")

            # 精度选择改变时,动态更新时间戳显示
            precision.change(
                lambda precision: get_current_timestamp(precision),
                inputs=precision,
                outputs=timestamp_input
            )

            # 时间戳转日期按钮点击事件
            def handle_timestamp_to_date(timestamp_input, target_timezone, precision):
                if timestamp_input:  # 如果时间戳输入框有内容
                    return timestamp_to_date(timestamp_input, target_timezone, precision)
                return "Please enter a valid timestamp"


            timestamp_to_date_btn.click(
                handle_timestamp_to_date,
                inputs=[timestamp_input, target_timezone, precision],
                outputs=output
            )

            # 日期转时间戳按钮点击事件
            def handle_date_to_timestamp(date_input, target_timezone):
                if date_input:  # 如果日期输入框有内容
                    return date_to_timestamp(date_input, target_timezone)
                return "Please enter a valid date"


            date_to_timestamp_btn.click(
                handle_date_to_timestamp,
                inputs=[date_input, target_timezone],
                outputs=output
            )

        with gr.Tab("Html Rendering"):
            with gr.Row():
                html_input = gr.Textbox(label="Html Data", interactive=True, placeholder="<html></html>", lines=50)
                html_output = gr.HTML()

        html_input.change(fn=html_format, inputs=html_input, outputs=html_output)

        with gr.Tab("Markdown Rendering"):
            with gr.Row():
                md_input = gr.Textbox(label="Markdown Data", interactive=True, placeholder="## title", lines=50)
                md_output = gr.Markdown()

        md_input.change(fn=md_format, inputs=md_input, outputs=md_output)

demo.launch()