package main_package;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;

import org.primefaces.model.UploadedFile;


public class DataBaseMethodsBackUpModule 
{
	static String dbName;
	static DataBaseMethods dbm=new DataBaseMethods();
	public DataBaseMethodsBackUpModule() 
	{
		dbName="gwit_db";
		//System.out.println("My Db: "+dbName);
		
	}
	
	public static boolean restoreDB(String fileName) 
	{  
		//System.out.println("restore Method called");
		String user="root";
		String psd="freelancer";
		String path=fileName;
		String[] executeCmd = new String[]{"mysql.exe", "--user=" + user, "--password=" + psd, dbName,"-e", "source "+path};  
		//System.out.println("restore path: "+path);
		Process runtimeProcess;  
		try 
		{  
			runtimeProcess = Runtime.getRuntime().exec(executeCmd);  
			int processComplete = runtimeProcess.waitFor();  
			//System.out.println(processComplete);
			if (processComplete == 0) 
			{  
				//System.out.println("hello");
			    return true;  
			} 
		}
		catch (Exception ex) {  
	            ex.printStackTrace();  
	    }  
	    return false;  
	}
	
	@SuppressWarnings("deprecation")
	public static boolean backUp(){
		
		 Date date=null;
		 String name=null;
		 try {
			 date=new Date();
			 	int day=date.getDate();
			 	int month=date.getMonth()+1;
			 	Calendar cal = Calendar.getInstance();
		    	cal.getTime();
		    	SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
		    	String s=sdf.format(cal.getTime()) ;
		    	String[] len=s.split(":");
		    	String hour=len[0];
		    	String min=len[1];
		    	String sec=len[2];
		    	int year=cal.get(Calendar.YEAR);
		    	//fileName=uploadFile;
		    	Connection conn=DataBaseConnection.JAVAConnection();
		    	String realPath="";
		    	if(dbm.fileUploadPathDetail()==null || dbm.fileUploadPathDetail().equalsIgnoreCase(""))
		    	{
		    		ServletContext ctx = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
					//String realPath = ctx.getRealPath("/")+folderName;
					realPath = ctx.getRealPath("/");
		    	}
		    	else
		    	{
		    		realPath=dbm.fileUploadPathDetail();
		    	}
				
				 
		    	name=dbName+"_Backup_"+day+"_"+month+"_"+year+"_"+hour+"_"+min+"_"+sec+".sql";
		       String name1=realPath+name;
			 
				try {
					Timestamp date1=new Timestamp(date.getTime());
					Statement stmt=conn.createStatement();
					String qu="insert into backuptable (fileName,date) values('"+name+"','"+date1+"')";
					stmt.executeUpdate(qu);
				
				} catch (SQLException e) {
					e.printStackTrace();
				}
				finally{
					try {
						conn.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
			 	
				System.out.println(name1);
				Process runProcess = Runtime.getRuntime().exec("mysqldump.exe -uroot -pfreelancer "+dbName+" -r\""+name1);
				int processComplete;
				try {
					processComplete = runProcess.waitFor();
					if (processComplete == 0) { 
						
						return true;  
					} 
					else
					{
						System.out.println("error in backup creation !!!!!");
					}
					
				} catch (InterruptedException e) {
					e.printStackTrace();
				} 
			} catch (IOException e) {
				e.printStackTrace();
			}
		
		 return false; 
	}
	
	public ArrayList<BackUp> showFileName(){
		ArrayList<BackUp> list=new ArrayList<BackUp>();
		Connection conn=DataBaseConnection.JAVAConnection();
		try {
			Statement stmt=conn.createStatement();
			String qu="select * from backuptable";
			ResultSet rs=stmt.executeQuery(qu);
			while(rs.next()){
				BackUp b=new BackUp();
				b.setDate(rs.getString("date"));
				b.setFileName(rs.getString("fileName"));
				b.setId(rs.getString("id"));
				list.add(b);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally
		{
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return list;
	}
	
	public void makeScanPath(UploadedFile file)
	{
		//String folderName="first\\";
		ServletContext ctx = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
		String realPath = ctx.getRealPath("/");
		//String realPath = ctx.getRealPath("/");
		//String savePath="D:\\";
		String fileName=file.getFileName();
		//System.out.println(fileName+"....."+realPath);
		try
		{
			InputStream in=file.getInputstream();
			OutputStream out = new FileOutputStream(new File(realPath + fileName));
          
			int read = 0;
			byte[] bytes = new byte[1024];
			
			while ((read = in.read(bytes)) != -1) {
				out.write(bytes, 0, read);
			}
      
			in.close();
			out.flush();
			out.close();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
}

