package com.stonecrusher.infrawhatsappmsg;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import com.fasterxml.jackson.databind.ObjectMapper;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class SendWhatsAppMessage {
	
	
	public static final String sendMessageOnly(String userName, String mobileNumber, String message, String token)
	{
		String reponse = "";
		
		try
		{
		
		String data = "";
		
		data += "username="+URLEncoder.encode(userName,"UTF-8");
		data += "&number="+URLEncoder.encode("91"+mobileNumber,"UTF-8");
		data += "&message="+URLEncoder.encode(message, "UTF-8");
		data +=  "&token="+URLEncoder.encode(token, "UTF-8");
		
		// data = java.net.URLEncoder.encode(data, "UTF-8");
		
		 URL url = new URL("https://int.chatway.in/api/send-msg?"+data);
	      		OkHttpClient client = new OkHttpClient();

		 		Request request = new Request.Builder()
		 			    .url(url)
		 			    .build();

		 			Response response = client.newCall(request).execute();
		 			 reponse = response.body().string();
		 			
		 			
		        
	         /*  URLConnection conn = url.openConnection();
	           conn.setDoOutput(true);
	           OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
	           wr.write(data);
	           wr.flush();
	           // Get the response
	           BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
	           String line;
	         
	           while ((line = rd.readLine()) != null) 
	           {
	                 // Process line...
	        	   resp=resp+line+" ";
	           }
	           wr.close();
	           rd.close();*/
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return reponse;
		
	}
	
	public static final String sendMessageWithFile(String userName, String mobileNumber, String message, String token, 
			String fileUrl, String fileName)
	{
		String reponse = "";
		
		try
		{
		
		String data = "";
		
		data += "username="+URLEncoder.encode(userName,"UTF-8");
		data += "&number="+URLEncoder.encode("91"+mobileNumber,"UTF-8");
		data += "&message="+URLEncoder.encode(message, "UTF-8");
		data +=  "&token="+URLEncoder.encode(token, "UTF-8");
		String safeFileName = fileName;
		if(safeFileName == null || safeFileName.trim().isEmpty())
		{
			safeFileName = "bill.pdf";
		}
		
		String rawData = data + "&file_url="+fileUrl+"&file_name="+safeFileName;
		String encodedData = data + "&file_url="+URLEncoder.encode(fileUrl, "UTF-8")+"&file_name="+URLEncoder.encode(safeFileName, "UTF-8");

	
		 URL url = new URL("https://int.chatway.in/api/send-file?"+encodedData);
	           
		 		//System.out.println(url);
		 		OkHttpClient client = new OkHttpClient();

		 		Request request = new Request.Builder()
		 			    .url(url)
		 			    .build();

		 			Response response = client.newCall(request).execute();
		 			 reponse = response.body().string();
		 			
		 			if(isFailedResponse(reponse))
		 			{
		 				URL rawUrl = new URL("https://int.chatway.in/api/send-file?"+rawData);
		 				Request rawRequest = new Request.Builder()
		 					    .url(rawUrl)
		 					    .build();
		 				Response rawResponse = client.newCall(rawRequest).execute();
		 				String rawResp = rawResponse.body().string();
		 				if(!isFailedResponse(rawResp))
		 				{
		 					reponse = rawResp;
		 				}
		 			}
		 		
	         /*  URLConnection conn = url.openConnection();
	           conn.setDoOutput(true);
	           OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
	           wr.write(data);
	           wr.flush();
	           // Get the response
	           BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
	           String line;
	         
	           while ((line = rd.readLine()) != null) 
	           {
	                 // Process line...
	        	   resp=resp+line+" ";
	           }
	           wr.close();
	           rd.close();*/
		}
		catch(Exception e)
		{
			e.printStackTrace();
			reponse = "ERROR: " + e.getMessage();
		}
		return reponse;
		
	}
	
	private static boolean isFailedResponse(String response)
	{
		if(response == null)
		{
			return true;
		}
		String value = response.trim().toLowerCase();
		return value.isEmpty() || value.contains("error") || value.contains("failed") || value.contains("invalid");
	}

}
