package com.weatherdemo.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;

import javax.net.ssl.HttpsURLConnection;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import com.weatherdemo.DB.Config; 

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.weatherdemo.Weather.Weather;

public class WeatherAdapter {

	private static Bitmap GetURLBitmap(String urlString ){
		URL url = null;
		Bitmap bitmap = null;
		try{
			url = new URL(urlString);
		}
		catch(MalformedURLException e){
			e.printStackTrace();
		}

		try{
			HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
			conn.connect();
			InputStream is = conn.getInputStream();
			bitmap = BitmapFactory.decodeStream(is);
			is.close();
		}catch(IOException e){
			e.printStackTrace();
		}
		return bitmap;
	}

//	//获取天气信息
//	public static void GetWeatherData(){
//		try{
//			//设置输入城市的编码，满足百度API需要
//			String xml = GetXmlCode(URLEncoder.encode(Config.CityName, "utf-8"));
//			//xml解析函数
//			ReadStringXml(xml, Config.CityName);
//		}catch(Exception e){
//			e.printStackTrace();
//		}
//	}
//
//	//获取xml
//	private static String GetXmlCode(String city)throws UnsupportedEncodingException{
//		String requestUrl = 
//				"http://api.map.baidu.com/telematics/v3/weather?location=" +
//						city + "&output=xml&ak=E572a10195a895f9af503a25d10e70e0";
//		StringBuffer buffer = null;
//		try{
//			//建立连接
//			URL url = new URL(requestUrl);
//			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//			conn.setDoInput(true);
//			conn.setRequestMethod("GET");
//
//			//获取输入流
//			InputStream is = conn.getInputStream();
//			InputStreamReader inputStreamReader = new InputStreamReader(is, "utf-8");
//			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
//
//			//读取返回结果
//			buffer = new StringBuffer();  
//			String str = null;  
//			while ((str = bufferedReader.readLine()) != null) {  
//				buffer.append(str);  
//			}  
//
//			// 释放资源  
//			bufferedReader.close();  
//			inputStreamReader.close();  
//			is.close();  
//			conn.disconnect();  
//		} catch (Exception e) {  
//			e.printStackTrace();  
//		}  
//		return buffer.toString();  //返回获取的xml字符串
//	}
//	
//	private static void ReadStringXml(String xml, String ifcity){
//		Document doc = null;
//		List listdate=null; //用来存放日期
//
//		List listday=null; //用来存放白天图片路径信息
//
//		List listweather=null;
//
//		List listwind=null;
//
//		List listtem=null;
//		try {
//			//读取解析XMl文档
//			doc = DocumentHelper.parseText(xml);//将字符串转化为xml
//			Element rootElt = doc.getRootElement();//获取根节点
//			Iterator iter = rootElt.elementIterator("results");//获取根节点下results节点
//			String status = rootElt.elementText("status");//获取叶子节点status数据
//			if(!status.equals("success")){
//				System.out.println("访问出错");
//				return;
//			}
//			String date = rootElt.elementText("date");//获取根节点下当天时间
//			Weather.forecast_date = date;
//			
//			//遍历results节点
//			while(iter.hasNext()){
//				Element recordEle = (Element) iter.next();
//				Weather.city = recordEle.elementText("currentCity");
//				Iterator iters = recordEle.elementIterator("weather_data");
//				
//				Iterator index = recordEle.elementIterator("index");
//				Element indexEle = (Element) index.next();
//				Weather.current_humidity = (String) indexEle.elements("des").get(0);
//				
//				while(iters.hasNext()){
//					Element itemEle = (Element) iters.next();
//					listdate = itemEle.elements("date");
//					listday=itemEle.elements("dayPictureUrl");
//					listweather=itemEle.elements("weather");
//					listwind=itemEle.elements("wind");
//					listtem=itemEle.elements("temperature");	
//				}
//				for(int i=0; i<listdate.size();i++){ //由于每一个list.size都相等，这里统一处理
//
//					Element eledate=(Element)listdate.get(i); //依次取出date
//					Element eleday=(Element)listday.get(i);//..
//					Element eleweather=(Element)listweather.get(i);
//					Element elewind=(Element)listwind.get(i);
//					Element eletem=(Element)listtem.get(i); 
//					
//					if(i == 0){
//						Weather.current_date_time = eledate.getText();
//						Weather.current_condition = eleweather.getText();
//						Weather.current_temp = eletem.getText();
//						Weather.current_image_url = eleday.getText();
//						Weather.current_image = getURLBitmap(eleday.getText());
//						Weather.current_wind = elewind.getText();						
//					}
//					else{
//						Weather.day[i-1].day_of_week = eledate.getText();
//						Weather.day[i-1].high = eletem.getText();
//						Weather.day[i-1].image_url = eleday.getText();
//						Weather.day[i-1].image = getURLBitmap(eleday.getText());
//						Weather.day[i-1].condition = eleweather.getText();
//					}
//					
//				} 
//			}
//		} catch (Exception e) {
//			// TODO: handle exception
//			e.printStackTrace();
//		}
//	}
	
	public static void GetWeatherData() throws IOException, Throwable {

    	String queryString = "http://www.google.com/ig/api?weather=" + Config.CityName;

    	URL aURL = new URL(queryString.replace(" ", "%20"));
     	URLConnection conn = aURL.openConnection();
        conn.connect();
        InputStream is = conn.getInputStream();
         
      	XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        factory.setNamespaceAware(true);
        XmlPullParser parser = factory.newPullParser();
        parser.setInput(is,"UTF-8");
        
        int dayCounter = 0;
        while(parser.next()!= XmlPullParser.END_DOCUMENT){
  
        	String element = parser.getName(); 
        	if (element != null && element.equals("forecast_information")){
        		while(true){
        			int eventCode = parser.next();
        			element =  parser.getName();
        			if (eventCode == XmlPullParser.START_TAG){
        				if (element.equals("city")){
    	            		Weather.city =  parser.getAttributeValue(0);
        				}else if (element.equals("current_date_time")){ 
        					Weather.current_date_time = parser.getAttributeValue(0);  
        				}
        			}
        			
        			if (element.equals("forecast_information") && 
        					eventCode == XmlPullParser.END_TAG){
        				break;
        			}
        		}    		
        	}
        	if (element != null && element.equals("current_conditions")){
        		while(true){
        			int eventCode = parser.next();
        			element =  parser.getName();
        			if (eventCode == XmlPullParser.START_TAG){
        				if (element.equals("condition")){
    	            		Weather.current_condition =  parser.getAttributeValue(0);
        				}else if (element.equals("temp_f")){ 
        					Weather.current_temp = parser.getAttributeValue(0);  
        				}else if (element.equals("humidity")){ 
        					Weather.current_humidity = parser.getAttributeValue(0);  
        				}else if (element.equals("wind_condition")){ 
        					Weather.current_wind = parser.getAttributeValue(0); 
        				}else if (element.equals("icon")){ 
        					Weather.current_image_url = parser.getAttributeValue(0);  
        					Weather.current_image = GetURLBitmap(Weather.current_image_url);
        				}
        			}
        			
        			if (element.equals("current_conditions") && 
        					eventCode == XmlPullParser.END_TAG){
        				break;
        			}
        		}    		
        	}
        	if (element != null && element.equals("forecast_conditions")){
        		while(true){
        			int eventCode = parser.next();
        			element =  parser.getName();
        			if (eventCode == XmlPullParser.START_TAG){
        				if (element.equals("day_of_week")){
    	            		Weather.day[dayCounter].day_of_week =  parser.getAttributeValue(0);
        				}else if (element.equals("low")){ 
        					Weather.day[dayCounter].low = parser.getAttributeValue(0);  
        				}else if (element.equals("high")){ 
        					Weather.day[dayCounter].high = parser.getAttributeValue(0);  
        				}else if (element.equals("icon")){ 
        					Weather.day[dayCounter].image_url = parser.getAttributeValue(0); 
        					Weather.day[dayCounter].image = GetURLBitmap(Weather.day[dayCounter].image_url);
        				}else if (element.equals("condition")){ 
        					Weather.day[dayCounter].condition = parser.getAttributeValue(0);  
        				}
        			}
        			
        			if (element.equals("forecast_conditions") && 
        					eventCode == XmlPullParser.END_TAG){
        				dayCounter++;
        				break;
        			}
        		}    
        	}
        	
        }       
        is.close();
	}
}
