package com.qiyou.mb.android.ui.fragments;

import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.baidu.mapapi.map.Polyline;
import com.qiyou.mb.android.QiYouConstant;
import com.qiyou.mb.android.R;
import com.qiyou.mb.android.service.QNaviSvc;
import com.qiyou.mb.android.service.TrackPlaybackService;
import com.qiyou.mb.android.utils.base.IlocationFragment;
import com.qiyou.mb.android.utils.enums.WorkingTrackType;
import com.qiyou.mb.android.utils.log.QLog;

public class Playback_fragment extends Track_fragment implements IlocationFragment  {
//	public static final String TAG ="com.qiyou.Playback_fragment";
	@Override
	public void setFTag(){
		TAG="com.qiyou.Playback_fragment";
	}
	public static String getFTag(){
		return "com.qiyou.Playback_fragment";
	}
	@Override
	public String getCurrentTag(){
		return "com.qiyou.Playback_fragment";
	}
//	boolean isStartPlay =false; 
//	boolean isPlayPause =false; 
	int playbackID =0;
	public Playback_fragment() {
		// TODO Auto-generated constructor stub
		workingTrackType= WorkingTrackType.PLAYBACK;
	}
	public static Playback_fragment newInstance(int trackId)
	{
		Playback_fragment f = new Playback_fragment();		
		if( trackId<=0) return f;
		Bundle args = new Bundle(); 
	    args.putInt(QiYouConstant.EXTRA_KEY_ID, trackId);
	    f.setArguments(args);
	    return f;
	}
	
	 
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState); 
//	   	 activity.app.currentActiveFragment =TAG;
//		 currentLayout =R.layout.playbackmap_fragment;
//		activity.app.playbackPaused =  true;
		if(activity==null){
			    activity = (com.qiyou.mb.android.ui.MainActivity)getActivity();
			}
		isPlaying=true;			 
		
	}
	private TextView tbs_playback_time;
	
	private String PLAY_START;
	private String PLAY_END;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) { 
		isPlayback =activity.app.playBack;
//		if(vContainer==null)
//			vContainer = inflater.inflate(R.layout.playbackmap_fragment, container, false);	
//	 		vContainer.findViewById(R.id.tm_fragment_container_details).setVisibility(View.GONE);//gone	
	  
	 	
//		View vContainer =super.onCreateView(inflater, container, savedInstanceState);
//		vContainer.findViewById(R.id.pl_fragment_container_details).setVisibility(View.GONE);//gone
//		vContainer.findViewById(R.id.pl_textView_bearing).setVisibility(View.GONE);
		//  vContainer.findViewById(R.id.pl_chronometer_sport)
		super.onCreateView(inflater, container, savedInstanceState);
		tbs_playback_time = (TextView) vContainer.findViewById(R.id.tbs_playback_time);
		tbs_playback_time.setText("时间快照");	
		activity.updateActionBarTitle(activity.app.isNaving?R.string.frg_snavi:R.string.frg_playback);
		initialSeekbar();
	    btnPlaySpeech = (ImageButton) vContainer.findViewById(R.id.pl_btnSpeech);
	    btnPlaySpeech.setOnClickListener(ButtonOnClickListener); 
	    vContainer.findViewById(R.id.ll_right_btns).setVisibility(View.GONE);
	    vContainer.findViewById(R.id.ll_liveshareMsg).setVisibility(View.GONE);
	   
	      btnMapLive.setVisibility(View.GONE);
		  btnLiveList.setVisibility(View.GONE);
		  btnMapLoadRoadbook.setVisibility(View.GONE);
		 
 	   QLog.getLogger().d(dTAG, TAG+ String.format(" ----- ll_right_btns is visible? %s  ",vContainer.findViewById(R.id.ll_liveshareMsg).getVisibility()==View.VISIBLE  ));

		return vContainer;
		
		}
	 
	/* protected void initialViews(){
	   super.initialViews(); 
	   
	 }*/
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState); 
 		activity.app.playbackPaused =  true;     
//		activity.startNaviService();
		  Bundle bd =this.getArguments();
		     if(bd!=null) 
		    	 playbackID = bd.getInt(QiYouConstant.EXTRA_KEY_ID) ;
//	      if(activity.app.currentTrackId ==playbackID) updateUI(new Location("initial"), false ); //draw the track
		     showPlaybackButtons();
//		     mSpeedText.setText( "回放就绪") ;
		     PLAY_START =activity.app.isNaving?"模拟开始":"回放开始"; 
		     PLAY_END=activity.app.isNaving?"模拟结束":"回放结束"; 
		     startStopPlay();
		     if(tabhost!=null ){
		    	 tabhost.setCurrentTab(1);
		     }
	}
 
	protected void showFullMap(){
//		FrameLayout ll  = (FrameLayout)vContainer.findViewById(R.id.playback_fragment_container_details);
//		ll.setVisibility(ll.getVisibility()==View.GONE?View.VISIBLE:View.GONE);
		  
				 LinearLayout footmark =(LinearLayout)vContainer.findViewById(R.id.tab_footmark); 
//				 ((LinearLayout)vContainer.findViewById(R.id.tab_footmark)).setVisibility(View.INVISIBLE);
				if(footmark!=null) footmark.setVisibility( View.INVISIBLE );
				 if(this.btnLocation!=null)
						btnLocation.setVisibility(View.GONE);
	}
	  
	
  @Override
protected  void startStopPlay(){
    	
    	isStartPlay =!isStartPlay;
    	if(isStartPlay){  
    		 mSpeedText.setText(PLAY_START ) ;
    		 if(QiYouConstant.PV_INT_NAVI_SPEAK_MODEL!=2)
    			 activity.app.speech(PLAY_START,0);
     		isPlayPause =false;
		    activity.app.playBackStopped =false;  
    		btnPlay.setImageResource(R.drawable.icon_plstop);
//		    btnPlay.setImageResource(R.drawable.stop);
//    		btnPlayMap.setText("停止");
    		activity.app.playbackPaused = false;    		
			btnPlayPause.setImageResource(R.drawable.icon_plpause);
//			
//    		gpRecordingOverlay.removeAll();
    		
    		activity.startTrackPlayBack(playbackID);
    		/*if(activity.app.isNaving){
    			startNavi(true);
    		}*/
    		  playbackSumPausetime=0;
    		  playbackSumOfftime=0;
    		  mTopSpeedText.setText("0.00"); 
//     		activity.app.initialPlayBack(playbackID);
    		  
    		  removeShortLines(); 
     		 
    	}else
    	{
    		 mSpeedText.setText(PLAY_END ) ;
    		 if(activity.app.isSpeaking())
    			 activity.app.stopSpeech();
    		 if(QiYouConstant.PV_INT_NAVI_SPEAK_MODEL!=2) 
    			 activity.app.speech(PLAY_END,0);
    		
    		 Intent serviceIntent = new Intent(activity, TrackPlaybackService.class);	
    		 activity.stopService(serviceIntent);
    		 
    		 if(activity.app.isNaving){
    			 serviceIntent = new Intent(activity, QNaviSvc.class);	
    			 activity.stopService(serviceIntent);
    		 }

    		 
    		 
    		 activity.app.playBack=false;
    		activity.app.playBackStopped =true; 
    		activity.app.playbackPaused =false;
    		btnPlay.setImageResource(R.drawable.icon_play);
//    		btnPlayMap.setText("开始");
    		btnPlayPause.setImageResource(R.drawable.icon_plpause);
    	}
    	 newTarget=-1;
		 oldprogress=-1;
		 activity.app.playProgressTarget=0;
    	btnPlayPause.setEnabled(isStartPlay);
    	QiYouConstant.CAN_SPEAK  = isStartPlay ;
//		btnPlay.setEnabled(false);
    	
    	
    	
    }
	//开始/停止按钮	    
	@Override
	protected void playbackPause(){
		isPlayPause =!isPlayPause;
		
	    	if (isPlayPause) {				
	    		activity.app.playbackPaused =  true;
				btnPlayPause.setImageResource(R.drawable.icon_plresume);
//				btnPlayPauseMap.setText("继续");	
				  tm_textView_bearing.setVisibility(View.GONE);
				   
			} else {					
				
				activity.app.playbackPaused = false;
				btnPlayPause.setImageResource(R.drawable.icon_plpause);
//				btnPlayPauseMap.setText("暂停");
				 
			}  
	    	 QiYouConstant.CAN_SPEAK  = !isPlayPause ;
	    	mSpeedText.setText(isPlayPause?"回放暂停":"回放继续") ;
	    } 
	 

	
		private SeekBar playControl = null;
		private SeekBar playSpeed = null;		
		private void initialSeekbar(){
			
			playSpeed = (SeekBar) vContainer.findViewById(R.id.pl_speed_bar);
			int span=activity.app.getCurrentTrack().getTrackBean().getGpsSpan();
			span=span>0?span:1000;
			final int max=30;
			playSpeed.setMax(max);	
			final int baseSpeed=5;
			final int speedStep=span/QiYouConstant.WPS_SAVE_PERCENT_FACTOR/max;  
			playSpeed.setProgress(max/2);
			QiYouConstant.PLAYBACK_TIME_INTERVAL =speedStep*max/2+baseSpeed*speedStep;
			playSpeed.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
				int progressChanged = 0; 
				@Override
				public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser){
					progressChanged = progress;
				}

				@Override
				public void onStartTrackingTouch(SeekBar seekBar) {
					// TODO Auto-generated method stub
				 
				}

				@Override
				public void onStopTrackingTouch(SeekBar seekBar) {
					progressChanged=progressChanged==0?1:progressChanged;
					progressChanged=progressChanged>1?progressChanged-1:progressChanged;
					 QiYouConstant.PLAYBACK_TIME_INTERVAL=(max-progressChanged)*speedStep +baseSpeed*speedStep;;
// 					Toast.makeText(activity,"seek bar progress:"+progressChanged,  	Toast.LENGTH_SHORT).show();
				}
			});
			int sumdist = (int) activity.app.getCurrentTrack().getTrackBean().getDistance();
			QLog.getLogger().d(dTAG, "sumdist is " + sumdist);
			playControl = (SeekBar) vContainer.findViewById(R.id.pl_progress_bar);
			playControl.setMax(sumdist);	
//			playControl.setEnabled(!activity.app.isNaving);//when naving,disable the seek
			playControl.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
				int progressChanged = 0;

				@Override
				public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser){
					progressChanged = progress;
				}

				@Override
				public void onStartTrackingTouch(SeekBar seekBar) {
					// TODO Auto-generated method stub
					oldprogress =seekBar.getProgress();
				}

				@Override
				public void onStopTrackingTouch(SeekBar seekBar) {
					activity.app.playProgressTarget =progressChanged;
					newTarget=progressChanged;
//					Toast.makeText(activity,"seek bar progress:"+progressChanged,  	Toast.LENGTH_SHORT).show();
				}
			});

		}
		
	
		int oldprogress=-1;
		int newTarget=-1;
	   @Override
    	public void updateUI(Location location, Boolean isOnPause){ 
		   if( isPlayPause||activity.app.playbackPaused )return;
		   if(location==null)return;
		   float speed =location.getSpeed();   
		   if(speed>-1 && (location.getExtras()==null||!location.getExtras().containsKey("wptime")))return; //filter locaitons from gps
		   float progress  = speed==-1?playControl.getMax() : location.getExtras().getFloat("dist")  ;
		   
		   if (playControl.getMax() == 0 ){
			    int sumdist = (int) activity.app.getCurrentTrack().getTrackBean().getDistance();
				QLog.getLogger().d(dTAG, "sumdist is " + sumdist);
				playControl = (SeekBar) vContainer.findViewById(R.id.pl_progress_bar);
				playControl.setMax(sumdist);	
		   }
		
		   
//		   if(progress==0)return;    	
//	    	progress =speed==-1?playControl.getMax():progress;
//		   QLog.getLogger().d(dTAG, TAG+ String.format("progress?%f,oldprogress?%s,newTarget?%s  ",progress,oldprogress,newTarget  ));
	   	    if(newTarget==oldprogress  //no changes
	   	    		||newTarget>oldprogress &&progress>=newTarget //forward  
	   	    		|| newTarget<oldprogress &&progress<=oldprogress ){//backward 
	 	    	playControl.setProgress((int) progress);  
		   	    newTarget=-1;
		   	    oldprogress=-1;
	   	    }
	   	    
	    	if(isStartPlay && speed==-1){ //playback over 
//				 mSpeedText.setText("回放结束") ; 
//				 activity.app.speech("回放结束",0);
				 mSpeedText.setText(PLAY_END) ; 
				 activity.app.speech(PLAY_END,0);
				 QiYouConstant.CAN_SPEAK  = false ;
				  tm_textView_bearing.setVisibility(View.GONE);
				  btnPlay.setImageResource(R.drawable.icon_play);
//				  btnPlay.setImageResource(R.drawable.play);
//		    	  btnPlayMap.setText("开始"); 
		    	  btnPlayPause.setEnabled(false);
		    	  isStartPlay=false;
		    	  activity.stopNaviService();
 
			 }else	
				 super.updateUI(location,isOnPause); 
    	}
	   @Override
	   protected void setWorkingTrack(){
		   mTrack =activity.app.getCurrentTrack();
		   mTrack_bean = mTrack.getTrackBean();
//		   QLog.getLogger().d(dTAG, " TrackId id:" +trackId +",mTrack_bean id is "+ mTrack_bean.getTrackId());
	   }
			 
//		    @Override
//		    protected void onRestoreInstanceState(Bundle savedInstanceState) {
//		    	super.onRestoreInstanceState(savedInstanceState);
//		    	mMapView.onRestoreInstanceState(savedInstanceState);
//		    }
 
	   
	    
		 
			@Override
			public void onResume() {
				super.onResume();
				isPlaying=true;
				isPlayback =activity.app.playBack;
//				QLog.getLogger().d(dTAG,"Is PlayBack?"+ isPlayback);
				
				activity.app.currentActiveFragment =getFTag();  
				
				
//				activity.app.playbackPaused =!isPlayback || !isStartPlay;
				activity.app.playbackPaused = !isStartPlay || isPlayPause;// !isStartPlay;		
				btnPlayPause.setEnabled(isStartPlay);
				showFullMap();
				showPlaybackButtons();
				activity.updateTabVisibility(false);
			}
			
			@Override
			public void onPause() {
				super.onPause();
				isPlaying=false;
 				activity.app.playbackPaused = isPlayback 
						&& !QiYouConstant.PV_BL_PLAYBACK_PAUSE_WITH_UI
						&& isStartPlay;

			}


			@Override
			public void onDestroy() {
	 
				isPlaying=false;
				activity.app.playBack=false;
				super.onDestroy();
			}

			@Override
			public void onSaveInstanceState(Bundle outState) {
				super.onSaveInstanceState(outState);
				 
			}

			@Override
			public void setTabOnFiling() {
				 MAPVIEW_INDEX=1;
				 maxTabIndex = 1;
				
			} 
	   
	   
	   
	   
	   
	   
	   
}










/*Handler myHandler = new Handler() {
    public void handleMessage(Message msg) {
        updateUIHere();
    }
}

new Thread() {
    public void run() {
        doStuff();         // 执行耗时操作
        Message msg = myHandler.obtainMessage();
        Bundle b = new Bundle();
        b.putString("key", "value");
        m.setData(b);    // 向消息中添加数据
        myHandler.sendMessage(m);    // 向Handler发送消息，更新UI
    }
}.start();*/




		    