package com.example.client;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cn.limc.androidcharts.entity.LineEntity;
import cn.limc.androidcharts.view.LineChart;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.PointF;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;

public class EvaluateActivity extends Activity implements OnClickListener {
    
    private Timer timer1s;  
    private int timeCount = 300;
    
    private static TextView mTimeTextView;
    private static TextView mTimeMention;
    
    private static TextView mXVTextView;
    private static TextView mSDNNTextView;
    private static TextView mHRVTextView;
    private static TextView mPNN50TextView;
    private static TextView mQZTextView;
    private static TextView mVLFTextView;
    private static TextView mLFTextView;
    private static TextView mHFTextView;
    
    LineChart machartCapture;
    List<LineEntity> lines;
    LineEntity lineQZ;
    LineEntity lineXV;
    LineEntity lineHRV;
    
    // 背景音乐控制
    private ImageButton mBgMusicButton;
    private Spinner mBgMusicSpinner;
    private boolean mIsFirst = true;
    
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.evaluate);
        
        Button back = (Button)findViewById(R.id.back_btn);
        back.setOnClickListener(this);
        
        mTimeTextView = (TextView) findViewById(R.id.labelTime);
        mTimeMention = (TextView) findViewById(R.id.timeMention);
        
        mXVTextView = (TextView) findViewById(R.id.labelXv);
        mSDNNTextView = (TextView) findViewById(R.id.labelSDNN);
        mHRVTextView = (TextView) findViewById(R.id.labelHRV);
        mPNN50TextView = (TextView) findViewById(R.id.labelPNN50);
        mQZTextView = (TextView) findViewById(R.id.labelQZ);
        mVLFTextView = (TextView) findViewById(R.id.labelVLF);       
        mLFTextView = (TextView) findViewById(R.id.labelLF);
        mHFTextView = (TextView) findViewById(R.id.labelHF);  
        
        // 定时器: 每隔1s更新一次曲线
        timer1s = new Timer();
        timer1s.schedule(new TimerTask(){
            @Override
            public void run() {         
                mHandler.post(mRunnable1s);
            }
        }, 1000, 1000);
        
        DrawData.clearIndexs();
        initMAChart();
        
        this.initBgMusic();
	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int id = v.getId();
		
		 if(id == R.id.back_btn){ 
			 this.finish();
		 }
	}
	
	
    private Runnable mRunnable1s = new Runnable() {
        @Override
        public void run() {
            mHandler.sendEmptyMessage(1);
            
            if (timeCount >= 0) {
            	mTimeMention.setText("距离评估结束还有" + Integer.toString(timeCount) + "秒.");
                mTimeTextView.setText(Integer.toString(timeCount--) + "s");
                
                EvaluateActivity.this.updateIndexs();
                
                lineXV.setLineData(DrawData.drawXV());
                lineQZ.setLineData(DrawData.drawQZ());
                lineHRV.setLineData(DrawData.drawHRV());
                machartCapture.setLineData(lines);
                machartCapture.setTouchPoint(new PointF(0.5f, 0.5f));
                machartCapture.notifyEvent(machartCapture);
                              
                if (timeCount < 0) {
                    // 测评结束
                    new AlertDialog.Builder(EvaluateActivity.this)   
                    .setTitle("确认")  
                    .setMessage("恭喜您完成测评!")  
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                        	EvaluateActivity.this.finish();
                        }
                    })  
                    .show(); 
                }
            } 
        }
    };
    
    
    private void updateIndexs()
    {
        int randHrv = (int)(Math.random() * 40);
        int randXv = 40 + (int)(Math.random() * 30);
        int randQz = 70 + (int)(Math.random() * 30);   
        int randSdnn = (int)(Math.random() * 100);      
        int randPnn50 = (int)(Math.random() * 100);      
        int randHF = (int)(Math.random() * 100);
        int randLF = (int)(Math.random() * 100);
        int randVLF = (int)(Math.random() * 100);
        
        mXVTextView.setText("心率:" + String.valueOf(randXv));
        mSDNNTextView.setText("SDNN:" + String.valueOf(randSdnn));
        mHRVTextView.setText("HRV:" + String.valueOf(randHrv));
        mPNN50TextView.setText("PNN50:" + String.valueOf(randPnn50));
        mQZTextView.setText("情指:" + String.valueOf(randQz));
        mVLFTextView.setText("VLF:" + String.valueOf(randVLF));   
        mLFTextView.setText("LF:" + String.valueOf(randLF));
        mHFTextView.setText("HF:" + String.valueOf(randHF)); 
        
        RelaxData.getInstance().setXV( randXv );
        RelaxData.getInstance().setQZ( randQz );
        RelaxData.getInstance().setSDNN( randSdnn );
        RelaxData.getInstance().setHRV( randHrv ) ;
        RelaxData.getInstance().setPNN50( randPnn50 );      
        RelaxData.getInstance().setHF( String.valueOf(randHF) );
        RelaxData.getInstance().setLF( String.valueOf(randLF) ) ;
        RelaxData.getInstance().setVLF( String.valueOf(randVLF) );
        
        UserInfo.getInstance().setRelaxName("评估");
    }
    
    
    private void initMAChart()
    {
        this.machartCapture = (LineChart)findViewById(R.id.machart);
        lines = new ArrayList<LineEntity>();
        
        // 心率曲线
        lineXV = new LineEntity();
        lineXV.setTitle("lineXV");
        lineXV.setLineColor(Color.RED);
        lineXV.setLineData(DrawData.drawXV());
        lines.add(lineXV); 
        
        // QZ曲线
        lineQZ = new LineEntity();
        lineQZ.setTitle("lineQZ");
        lineQZ.setLineColor(Color.CYAN);
        lineQZ.setLineData(DrawData.drawQZ());
        lines.add(lineQZ);        
        
        // HRV曲线
        lineHRV = new LineEntity();
        lineHRV.setTitle("lineHRV");
        lineHRV.setLineColor(Color.YELLOW);
        lineHRV.setLineData(DrawData.drawHRV());
        lines.add(lineHRV);  
        
        List<String> ytitle=new ArrayList<String>();
        ytitle.add("0");
        ytitle.add("20");
        ytitle.add("40");
        ytitle.add("60");
        ytitle.add("80");
        ytitle.add("100");
        ytitle.add("120");
        List<String> xtitle=new ArrayList<String>();
        xtitle.add("0");
        xtitle.add("40");
        xtitle.add("80");
        xtitle.add("120");
        xtitle.add("160");
        xtitle.add("200");
        
        machartCapture.setAxisXColor(Color.LTGRAY);
        machartCapture.setAxisYColor(Color.LTGRAY);
        machartCapture.setBorderColor(Color.LTGRAY);
        
        // 设置背景为透明
        machartCapture.setBackgroundColor(Color.TRANSPARENT);
        
        machartCapture.setAxisMarginTop(10);
        machartCapture.setAxisMarginBottom(30);
        machartCapture.setAxisMarginLeft(30);
        
        machartCapture.setAxisYTitles(ytitle);
        machartCapture.setAxisXTitles(xtitle);
        
        // 不显示坐标线
        machartCapture.setDisplayCrossXOnTouch(false);
        machartCapture.setDisplayCrossYOnTouch(false);
        
        // 纵轴标题大小  
        machartCapture.setLatitudeFontSize(16);
        // 横轴标题大小
        machartCapture.setLongitudeFontSize(16);
        
        machartCapture.setLongitudeFontColor(Color.WHITE);
        machartCapture.setLatitudeColor(Color.GRAY);
        machartCapture.setLatitudeFontColor(Color.WHITE);
        machartCapture.setLongitudeColor(Color.GRAY);
        
        // 校验大小：不在范围内不显示
        machartCapture.setMaxValue(255);
        machartCapture.setMinValue(0);
        machartCapture.setMaxPointNum(DrawData.FIGURE_LENGTH);
        
        machartCapture.setDisplayAxisXTitle(true);
        machartCapture.setDisplayAxisYTitle(true);
        machartCapture.setDisplayLatitude(true);
        machartCapture.setDisplayLongitude(true);
        
        //为chart1增加均线
        machartCapture.setLineData(lines);
    }
    
    
    private void initBgMusic()
    { 
        mBgMusicSpinner = (Spinner)findViewById(R.id.btnBgDrowdown);
        mBgMusicButton = (ImageButton)findViewById(R.id.btnBgCtrl);
                
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(EvaluateActivity.this, R.layout.simple_spinner_item);

        // 资源文件
        String bg[] = getResources().getStringArray(R.array.bg_music);
        for (int i = 0; i < bg.length; i++) 
        {
            adapter.add(bg[i]);
        }
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        
        mBgMusicSpinner.setAdapter(adapter);
        mBgMusicSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String str = parent.getItemAtPosition(position).toString(); 
                
                // 切换背景音乐
                // 系统会自动调用一次, 造成音乐自动播放
                if (!mIsFirst) {
                    BgMusic.getInstance().changeMusicEnv("/bgmusic/" + str + ".mp3", position);
                    mBgMusicButton.setImageResource(R.drawable.bg_pause);
                }
                mIsFirst = false;            
            }
            
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // TODO Auto-generated method stub
            }
        });
        
        // 开始播放背景音乐
        if (BgMusic.getInstance().isFirst()) {
            BgMusic.getInstance().start("/bgmusic/" + bg[0] + ".mp3");
        }
        
        // 初始化
        if (BgMusic.getInstance().isPlaying()) {
            mBgMusicButton.setImageResource(R.drawable.bg_pause);
        }
        else {
            mBgMusicButton.setImageResource(R.drawable.bg_play);
        } 
        
        // 设置当前曲目
        mBgMusicSpinner.setSelection(BgMusic.getInstance().getMusicIndex());
         
        // 控制按钮
        mBgMusicButton.setOnClickListener(new OnClickListener() {        
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                if (BgMusic.getInstance().isPlaying()) {
                    mBgMusicButton.setImageResource(R.drawable.bg_play);
                }
                else {
                    mBgMusicButton.setImageResource(R.drawable.bg_pause);
                } 
                BgMusic.getInstance().togglePlay();
            }
        });
    }
}
