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 com.qiyou.mb.android.QiYouConstant;
import com.qiyou.mb.android.content_providers.TrackProvider;
import com.qiyou.mb.android.utils.log.QLog;
  
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.widget.Toast;

public class Exportdb {
	public static String dTAG = "com.qiyou";
	public static String TAG = "com.qiyou.ExportDb";

	
 
//	 private static final String DATABASE_NAME = "tracks.db";
//	 private static final int DATABASE_VERSION = 7;
	 String destXml;	 
	private String mDestXmlFilename =  QiYouConstant.SD_PATH +"export.xml";
	private SQLiteDatabase mDb;
	private Exporter mExporter;
	String strWhere =" where 1=1 ";
	Context context;
	String _ids="";	
	void prepareExp(){
		/* 
		  PlacesDatabaseHelper dbHelper = new PlacesDatabaseHelper( context, DATABASE_NAME, 
                  null, DATABASE_VERSION);
//    	  File path = new File("/sdcard/qiyou");// 创建目录  
    	  File f = new File("/sdcard/qiyou/tracks.db");// 创建文件  
				try {
				//tracksDB = dbHelper.getWritableDatabase();
				 mDb =SQLiteDatabase.openOrCreateDatabase(f, null);  
				 
				} catch (SQLiteException e) {
					mDb = null;
				QLog.getLogger().d("ExportDB", "Database Opening exception");
				}
				*/ 
		
		
		mDb =  TrackProvider.getTracksDB(); 
				
		
	}
	
	public void ExportTracks(){
	
		 exportData() ;
	}
	
	public void ExportTracks(String[] ids){
		 
		 String strIn = "-1";
		 for(String id:ids){
			 strIn += "," + id;
				QLog.getLogger().d(dTAG,TAG+ "prepare export Track id of " + id);
				_ids+="_"+id;
		 }
//		 strWhere += " and _id in ("+strIn+")";
		 QLog.getLogger().d(dTAG,TAG+ " export strWhere: " + strWhere);
		 
		 exportData() ;
	}
	
	public Exportdb(Context ct){
		context =ct;
		prepareExp();
	}
	
	public Exportdb(SQLiteDatabase db, String destXml) { 

		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);
			BufferedOutputStream bos = new BufferedOutputStream(fOut);

			mExporter = new Exporter(bos);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	  void exportData() {

			try {
				// create a file on the sdcard to export the
				// database contents to
				mDestXmlFilename =  QiYouConstant.SD_PATH + "export"+ _ids+".xml";
				File myFile = new File(mDestXmlFilename);
				myFile.createNewFile();

				FileOutputStream fOut = new FileOutputStream(myFile);
				BufferedOutputStream bos = new BufferedOutputStream(fOut);

				mExporter = new Exporter(bos);
				
				
				mExporter.startDbExport(mDb.getPath());

				// get the tables out of the given sqlite database
				String sql = "SELECT * FROM sqlite_master";

				Cursor cur = mDb.rawQuery(sql, new String[0]);
				cur.moveToFirst();

				String tableName;
				while (cur.getPosition() < cur.getCount()) {
					tableName = cur.getString(cur.getColumnIndex("name"));

					// don't process these two tables since they are used
					// for metadata
					if (!tableName.equals("android_metadata")
							&& !tableName.equals("sqlite_sequence")) {
						exportTable(tableName);
					}

					cur.moveToNext();
				}
				mExporter.endDbExport();
				mExporter.close(); 
				
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		   
		 Toast toast=	Toast.makeText(context,"数据已导出至  "+mDestXmlFilename,Toast.LENGTH_SHORT );
		 toast.show(); 

	}

	private void exportTable(String tableName) throws IOException {
		mExporter.startTable(tableName);

		// get everything from the table
		String sql = "select * from " + tableName +  strWhere;
		 QLog.getLogger().d(dTAG,TAG+ " export sql: " + sql);
		Cursor cur = mDb.rawQuery(sql, new String[0]);
		int numcols = cur.getColumnCount();

		cur.moveToFirst();

		// move through the table, creating rows
		// and adding each column with name and value
		// to the row
		while (cur.getPosition() < cur.getCount()) {
			mExporter.startRow();
			String name;
			String val;
			QLog.getLogger().d(dTAG,
					TAG + " Start to process row with ID " + cur.getString(0));
			try{
				for (int idx = 0; idx < numcols; idx++) {
					name = cur.getColumnName(idx);
					val = cur.getString(idx);
					mExporter.addColumn(name, val);
				}
	
				mExporter.endRow();
				cur.moveToNext();
			}
			catch(IllegalStateException e){
				Utils.logStackTrace(e, dTAG);
				continue;
			}
			catch(Exception e){
				Utils.logStackTrace(e, dTAG);
			}
		}

		cur.close();

		mExporter.endTable();
	}



	class Exporter {
		private static final String CLOSING_WITH_TICK = "'>";
		private static final String START_DB = "<export-database name='";
		private static final String END_DB = "</export-database>";
		private static final String START_TABLE = "<table name='";
		private static final String END_TABLE = "</table>"+"\n";
		private static final String START_ROW = "<row>"+"\n";
		private static final String END_ROW = "</row>"+"\n";
		private static final String START_COL = "<col name='";
		private static final String END_COL = "</col>";

		private BufferedOutputStream mbufferos;

		public Exporter() throws FileNotFoundException {
			this(new BufferedOutputStream(
					new FileOutputStream(mDestXmlFilename)));

		}

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

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

		public void startDbExport(String dbName) throws IOException {
			String stg = START_DB + dbName + CLOSING_WITH_TICK;
			mbufferos.write(stg.getBytes());
		}

		public void endDbExport() throws IOException {
			mbufferos.write(END_DB.getBytes());
		}

		public void startTable(String tableName) throws IOException {
			String stg = START_TABLE + tableName + CLOSING_WITH_TICK;
			mbufferos.write(stg.getBytes());
		}

		public void endTable() throws IOException {
			mbufferos.write(END_TABLE.getBytes());
		}

		public void startRow() throws IOException {
			mbufferos.write(START_ROW.getBytes());
		}

		public void endRow() throws IOException {
			mbufferos.write(END_ROW.getBytes());
		}

		public void addColumn(String name, String val) throws IOException {
			String stg = START_COL + name + CLOSING_WITH_TICK + val + END_COL+"\n";
			mbufferos.write(stg.getBytes());
		}
	}
	
	
    // Helper class for opening, creating, and managing database version control
		  static class PlacesDatabaseHelper extends SQLiteOpenHelper {
		   
		        
		    public PlacesDatabaseHelper(Context context, String name, CursorFactory factory, int version) {
		      super(context, name, factory, version);
		    }

			@Override
			public void onCreate(SQLiteDatabase db) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onUpgrade(SQLiteDatabase db, int oldVersion,
					int newVersion) {
				// TODO Auto-generated method stub
				
			}

		 
		  }

}