package com.tcl.factory.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.json.JSONException;
import org.json.JSONObject;

import android.R.string;
import android.content.Context;
import android.widget.Toast;

import com.tcl.factory.bsp.TV;
import com.tcl.factory.bsp.TVDefine;
import com.tcl.factory.thirdparty.ThirdParty;




public class TestDeviceID {   
	private static String URI= "https://tvuser-tcl.cedock.com/uc/json" ;   //Default address is CN
	private String recevieJson = null;
	private String sendJson = null;
	public Context mContext=null;
	public  String code="error";
	
	public static  boolean bDeviceIDOK=false; //testDeviceID;

	public TestDeviceID(Context mcontext) 
	{
		mContext=mcontext;
		if(!TV.readS(TVDefine.NetworkConnectivity))
		{
			Debug.v("TestDeviceID", "Net is not ready ========"+bDeviceIDOK);
			Toast.makeText(mContext, "Net is not ready!",Toast.LENGTH_SHORT).show();
			bDeviceIDOK=false;
			return;
		}
		
		String mArea = ThirdParty.GetDeviceTestServerArea();
		if(mArea.equalsIgnoreCase("AS"))
		{
			URI="https://as-tvuser-tcl.cedock.com/uc/json";
		}
		else if(mArea.equalsIgnoreCase("EU"))
		{
			URI="https://eu-tvuser-tcl.cedock.com/uc/json";
		}
		else if(mArea.equalsIgnoreCase("NA"))
		{
			URI="https://na-tvuser-tcl.cedock.com/uc/json";
		}
		Debug.v("TestDeviceID", "DID URI=" + URI);
		Debug.v("TestDeviceID", "TestDeviceID is ========"+bDeviceIDOK);
		Toast.makeText(mContext, "DeviceID is testing...", Toast.LENGTH_SHORT).show();
		new Thread()
		{
			public void run() 
			{
				try
				{
					code=device_test();
				} 
				catch (Exception e) 
				{
					Debug.v("TestDeviceID", "Exception device_test");

				}
			};
		}.start(); 
	}
	/**
     *
     * @param
     * @return
     * @throws Exception
     */
	 public String device_test() throws Exception
	    {
	    	JSONObject my_object = new JSONObject();
	    	JSONObject new_child_obj = new JSONObject();
	    	
	    	my_object.put("action", "TestDevice");
	    	
	    	new_child_obj.put("deviceid", ThirdParty.getDeviceIDString());
	    	new_child_obj.put("devmodel",ThirdParty.getClientType());
	    	new_child_obj.put("devmac",ThirdParty.getMACAddressString());
	    	
	    	my_object.put("device", new_child_obj);
			String message = new String(my_object.toString());
			Debug.v("test device login send", message);
			String out_http_msg = do_https_request(URI, message);
	    	Debug.v("test device login", out_http_msg);
			return parser_test_device(out_http_msg);
	    	
	    }

	    public String do_https_request(String url, String strSendMsg) throws  Exception 
	    {
	    	
	    	SSLContext sc = SSLContext.getInstance("TLS");
	    	sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());
	    	URL pathurl = new URL(url);
	    	URLConnection conntest = pathurl.openConnection();
	    	
	    	if(conntest != null){
	    		Debug.v("URLConnection","connect fail");
	    	}
	    	HttpsURLConnection conn = (HttpsURLConnection)conntest;
	    	conn.setConnectTimeout(5000);
	    	conn.setSSLSocketFactory(sc.getSocketFactory());
	    	conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
	    	conn.setDoInput(true);
	    	conn.setDoOutput(true);
	     
	    	conn.setRequestMethod("POST");
	    	
	    	
	    	conn.connect();
	 
	    	conn.getOutputStream().write(strSendMsg.getBytes());
	    	String temp = "";
	    	String result = "";
	    	InputStreamReader inr = new InputStreamReader(conn
	    	.getInputStream(), "utf-8");
	    	BufferedReader br = new BufferedReader(inr);
	    	while((temp=br.readLine())!=null){
	    		Debug.v("return character","temp = "+temp);
	    	result += temp;
	    	}
	    	return result;
		}  
		 /**
	     *
	     * @param out_string
	     * @return
	     * @throws JSONException
	     */
	    public String parser_test_device(String out_string) throws JSONException
	    {
	    	String error_code = new String();
	    	JSONObject my_object = new JSONObject(out_string);
	    	int retv = 0;
	    	if(my_object.has("error"))
	    	{
	    		String error = new String(my_object.getString("error"));
	    		JSONObject error_object = new JSONObject(error);
	    		if(error_object.has("code"))
	    		{
	    			retv = error_object.getInt("code");
	    			if(0 == retv)
	    				error_code = "false";
	    			else
	    				error_code = "error_code:" + retv + "error_info:";
	    		}
	    		if(error_object.has("info") && error_code != "false")
	    		{
	    			error_code = error_code + error_object.getString("info");
	    			
	    		}
	    	}
	    	
			return error_code;
	    	
	    	
	    }

	public String getRecevieJson() {
		return recevieJson;
	}
	public void setRecevieJson(String recevieJson) {
		this.recevieJson = recevieJson;
	}
	public String getSendJson() {
		return sendJson;
	}
	public void setSendJson(String sendJson) 
	{
		this.sendJson = sendJson;
	}
	public boolean getTestDeviceStatus() {
		// TODO Auto-generated method stub
		try {
			Thread.currentThread().sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		if(!code.equalsIgnoreCase("false")){
			try {
				Thread.currentThread().sleep(1200);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		if(code.equalsIgnoreCase("false")||bDeviceIDOK)
		{
		 
				Toast.makeText(mContext, "Portal Test OK!",Toast.LENGTH_SHORT).show();
		    return     	bDeviceIDOK=true;
	
		}
		else{
		 
				Toast.makeText(mContext, "Portal Test Fail!",Toast.LENGTH_SHORT).show();
		     return    	bDeviceIDOK=false;
			
		}
	}

	public  static class TrustAnyTrustManager implements X509TrustManager
	{
		public void checkClientTrusted(X509Certificate[] chain, String authType)
		throws CertificateException {
			// TODO Auto-generated method stub

		}


		public void checkServerTrusted(X509Certificate[] chain, String authType)
		throws CertificateException 
		{
			// TODO Auto-generated method stub
		}

		public X509Certificate[] getAcceptedIssuers() 
		{
			// TODO Auto-generated method stub
			return new X509Certificate[]{};
		}

	}
	public static class TrustAnyHostnameVerifier implements HostnameVerifier
	{


		public boolean verify(String hostname, SSLSession session) 
		{
			// TODO Auto-generated method stub
			return true;
		}

	}
}