/*
 * 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.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.ProgressBar;
import android.widget.TextView;

import net.micode.notes.R;
import net.micode.notes.tool.AudioTool;

/**
 * 录音对话框
 */
public class AudioRecorderDialog extends Dialog implements View.OnClickListener {
    private static final int MAX_DURATION_MS = 60 * 1000; // 最大录音时长为1分钟
    private static final int UPDATE_INTERVAL = 100; // 更新进度间隔(毫秒)

    private TextView mStatusTextView;
    private Button mStartButton;
    private Button mStopButton;
    private Chronometer mChronometer;
    private ProgressBar mProgressBar;
    
    private Handler mHandler = new Handler();
    private Runnable mUpdateProgressTask;
    private long mStartTime = 0;
    private boolean mIsRecording = false;

    private OnAudioRecordListener mListener;

    /**
     * 录音完成回调接口
     */
    public interface OnAudioRecordListener {
        void onAudioRecorded(String audioFilePath);
    }

    public AudioRecorderDialog(Context context, OnAudioRecordListener listener) {
        super(context);
        this.mListener = listener;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.audio_recorder_dialog);
        setTitle(R.string.audio_record);

        // 初始化视图
        mStatusTextView = findViewById(R.id.tv_recording_status);
        mStartButton = findViewById(R.id.btn_start_recording);
        mStopButton = findViewById(R.id.btn_stop_recording);
        mChronometer = findViewById(R.id.chronometer);
        mProgressBar = findViewById(R.id.recording_progress);
        
        // 设置最大进度为录音最大时长
        mProgressBar.setMax(MAX_DURATION_MS);
        
        // 设置点击监听
        mStartButton.setOnClickListener(this);
        mStopButton.setOnClickListener(this);
        
        // 创建进度更新任务
        mUpdateProgressTask = new Runnable() {
            @Override
            public void run() {
                if (mIsRecording) {
                    long elapsedTime = SystemClock.elapsedRealtime() - mStartTime;
                    mProgressBar.setProgress((int) elapsedTime);
                    
                    // 如果达到最大时长，自动停止录音
                    if (elapsedTime >= MAX_DURATION_MS) {
                        stopRecording();
                    } else {
                        mHandler.postDelayed(this, UPDATE_INTERVAL);
                    }
                }
            }
        };
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_start_recording) {
            startRecording();
        } else if (v.getId() == R.id.btn_stop_recording) {
            stopRecording();
        }
    }

    /**
     * 开始录音
     */
    private void startRecording() {
        // 开始录音
        String recordFile = AudioTool.startRecording(getContext());
        if (recordFile != null) {
            mIsRecording = true;
            
            // 更新UI
            mStatusTextView.setText(R.string.audio_recording);
            mStartButton.setEnabled(false);
            mStopButton.setEnabled(true);
            
            // 开始计时
            mStartTime = SystemClock.elapsedRealtime();
            mChronometer.setBase(mStartTime);
            mChronometer.start();
            
            // 开始进度更新
            mHandler.post(mUpdateProgressTask);
        }
    }

    /**
     * 停止录音
     */
    private void stopRecording() {
        if (mIsRecording) {
            mIsRecording = false;
            
            // 停止计时
            mChronometer.stop();
            
            // 停止进度更新
            mHandler.removeCallbacks(mUpdateProgressTask);
            
            // 停止录音并获取录音文件路径
            String audioFilePath = AudioTool.stopRecording();
            
            // 回调录音完成事件
            if (mListener != null && audioFilePath != null) {
                // 提取文件名部分
                String fileName = audioFilePath.substring(audioFilePath.lastIndexOf('/') + 1);
                mListener.onAudioRecorded(fileName);
            }
            
            // 关闭对话框
            dismiss();
        }
    }

    @Override
    public void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        // 确保停止录音
        if (mIsRecording) {
            AudioTool.stopRecording();
        }
        mHandler.removeCallbacks(mUpdateProgressTask);
    }
} 