package com.qiyou.mb.android.utils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.CopyOnWriteArrayList;

//import org.alternativevision.gpx.GPXParser;
//import org.alternativevision.gpx.beans.GPX;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.widget.Toast;

import com.qiyou.mb.android.QiYouConstant;
import com.qiyou.mb.android.beans.Track;
import com.qiyou.mb.android.beans.basic.Waypoint_bean;
import com.qiyou.mb.android.utils.enums.TrackStatus;
import com.qiyou.mb.android.utils.log.QLog;

public class TrackInterface {
	public static final String TAG = "com.qiyou.mb.android.utils.TrackInterface";
	public static final String dTAG = "com.qiyou";
	
	public TrackInterface() {
		// TODO Auto-generated constructor stub
	}
	
	private String mDestXmlFilename =  QiYouConstant.SD_PATH +"export.xml";
	public String exportGPX(final Context context,final Track track)   {
		
		 /*final   Handler	 handler	= new Handler(){
				
				@Override
				public void handleMessage(Message msg) {
					
					//关闭ProgressDialog
//									progressDialog.dismiss(); 
					
					 //更新UI
//										 switchButtonStatus(); 
					
					  if(msg.what==1){
//						 
						  Toast.makeText(context,"数据已导出至  "+mDestXmlFilename,Toast.LENGTH_SHORT ).show();
					}else
					{
						Toast.makeText(context,"数据导出出现错误，导出失败。",Toast.LENGTH_SHORT ).show();
					}
					  
					  
					  
				}};*/
				
//		new Thread(){ 
//			@Override
//			public void run() {
			 try {
//				 
//				 int id =track.getTrackBean().getTrackId();
				 
			       File file=new File(QiYouConstant.EXP_PATH );
			        if(!file.exists()){ //在SD卡上创建目录：
			        	file.mkdir();
			        	QLog.getLogger().d(dTAG, "Utils: "+ "App Path created on SD as  "+ QiYouConstant.EXP_PATH);
			            
			        } 
//				mDestXmlFilename =  QiYouConstant.EXP_PATH + "GPX_"+ id+".gpx";
				mDestXmlFilename =  QiYouConstant.EXP_PATH + "GPX_"+ track.getTrackBean().getName()+".gpx";
				Exporter mExporter =new Exporter(mDestXmlFilename);  
				mExporter.startGPXExport();
			/*	CopyOnWriteArrayList<Waypoint_bean> wbs =track.getTrackBean().getTrkseg();
				CopyOnWriteArrayList<Waypoint_bean> rdwbs =track.getTrackBean().getRoadWps();*/
				 ArrayList<Waypoint_bean> wbs =track.getTrackBean().getTrkseg();
				 ArrayList<Waypoint_bean> rdwbs =track.getTrackBean().getRoadWps();
				String trackptFmt="\n<trkpt lat=\"%f\" lon=\"%f\">\n<ele>%.2f</ele>\n<time>%s</time>\n<speed>%.2f</speed>\n" +
						"<name>%s</name>\n"+
						"<cmt>%s</cmt>\n"+
						"<desc>%s</desc>\n"+
						"</trkpt>";
				String trackpt ;
				String cmt="";
				
				
				for(Waypoint_bean wb :wbs){
					if(wb==null)continue;
					int i=0;
					for(Waypoint_bean rdwb:rdwbs){
						i++;
						if(rdwb!=null && wb.getTime()==rdwb.getTime()){							
							wb=rdwb;
							break;
						}
					}
//					Waypoint_bean nextWb=i<rdwbs.size()?rdwbs.get(i):wb;
//					 cmt =!TextUtils.isEmpty(wb.getRoadBook())?wb.getRoadBook()+"\n"+wb.getComment() :wb.getComment();
//					 cmt =!TextUtils.isEmpty(nextWb.getRoadBook())?nextWb.getRoadBook()+"\n"+wb.getComment() :wb.getComment();
					cmt =!TextUtils.isEmpty(wb.getRoadBook())?wb.getRoadBook()+"\n"+wb.getComment() :wb.getComment();
					 if(cmt.startsWith("\""))cmt=cmt.substring(1,cmt.length());
					 if(cmt.endsWith("\""))cmt=cmt.substring(0,cmt.length()-1);
					 trackpt =String.format(trackptFmt,wb.getLatitude()
							 ,wb.getLongitude(),wb.getElevation()
							 ,Utils.getGPXformatedTime(wb.getTime())
							 ,wb.getSpeed()/3.6f
							 , wb.getName(),cmt,wb.getDesc());
					 mExporter.addTrkpt(trackpt);
				} 
				mExporter.endGPXExport(); 
//				handler.sendEmptyMessage(1);
				 
			} catch (IOException e) {
				// TODO Auto-generated catch block
				Utils.logStackTrace(e,dTAG);
//				handler.sendEmptyMessage(0);
				return null;
			}catch(Exception e){
				Utils.logStackTrace(e,dTAG);
//				handler.sendEmptyMessage(0);
				return null;
			}
			 return mDestXmlFilename;
//		 }}.start();  
		 
		 
	
		   
		 
				 
		/*GPXParser p = new GPXParser();
		FileOutputStream out;
		try {
			out = new FileOutputStream("outFile.gpx");
			GPX gpx = new GPX();
			 
//		p.writeGPX(gpx, out);
		out.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
	}
	
	class Exporter {
		 
		 
		private static final String XML_HEAD= "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
		private static final String GPX_HEAD="<gpx\n"
				+"version=\"1.0\"\n"
				+ "creator=\"爱骑驴\"\n"
				+ "xmlns=\"http://www.topografix.com/GPX/1/1\"\n"
				+ "xmlns:topografix=\"http://www.topografix.com/GPX/Private/TopoGrafix/0/1\"\n"
				+ "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
				+ "xsi:schemaLocation=\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd http://www.topografix.com/GPX/Private/TopoGrafix/0/1 http://www.topografix.com/GPX/Private/TopoGrafix/0/1/topografix.xsd\">\n"
				;
		private static final String GPX_META=
				"<metadata>\n"
				+"<name><![CDATA[爱骑驴]]></name>\n"
				+"<desc><![CDATA[]]></desc>\n"
				+"</metadata>\n"
				;
		private static final String GPX_TRK_START=
				"<trk>\n"
				+"<name><![CDATA[爱骑驴]]></name>\n"
				+"<desc><![CDATA[]]></desc>\n"
				+"<trkseg>"
				;
		private static final String GPX_TRK_END="\n</trkseg>\n</trk>\n</gpx>";

		private BufferedOutputStream mbufferos;

		public Exporter(String mDestXmlFilename) throws FileNotFoundException {
			
			try {
				// create a file on the sdcard to export the
				// database contents to
				File myFile = new File(mDestXmlFilename);
				myFile.createNewFile();

				FileOutputStream fOut = new FileOutputStream(myFile);
				mbufferos = new BufferedOutputStream(fOut);
//				this(new BufferedOutputStream( new FileOutputStream(mDestXmlFilename)));
			 
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			

		}
 
//		public Exporter(BufferedOutputStream bos) {
//			mbufferos = bos;
//		}

		public void close() throws IOException {
			if (mbufferos != null) {
				mbufferos.close();
			}
		}

		public void startGPXExport() throws IOException {
			String stg = XML_HEAD + GPX_HEAD + GPX_META +GPX_TRK_START;
			mbufferos.write(stg.getBytes());
		}

		public void endGPXExport() throws IOException {
			mbufferos.write(GPX_TRK_END.getBytes());
			close(); 
		}

		public void addTrkpt(String  trkpt) throws IOException {
//			String stg = trkpt;
			mbufferos.write(trkpt.getBytes());
		}
	 
	}
}
