package com.coolweather.app.db;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.coolweather.app.model.City;
import com.coolweather.app.model.Province;

public class CoolWeatherDB {
	/**
	 * Êý¾ÝÃû£¬Ãû³ÆÎª£ºcool_weather
	 */
	public static final String DB_NAME = "cool_weather";
	
	/**
	 * Êý¾Ý¿â°æ±¾£¬µ±Ç°°æ±¾ÊÇ1
	 */
	public static final int VERSION = 1;
	
	private static CoolWeatherDB coolWeatherDB;
	
	private SQLiteDatabase db;
	
	/**
	 * ½«¹¹ÔìË½ÓÐ»¯
	 */
	private CoolWeatherDB(Context context){
		CoolWeatherOpenHelper dbHelper = new CoolWeatherOpenHelper(context, DB_NAME, null, VERSION);
		db = dbHelper.getWritableDatabase();
	}
	
	/**
	 * µ¥ÀýÄ£Ê½£¬»ñÈ¡CoolWeatherDBÊµÀý
	 */
	public synchronized static CoolWeatherDB getInstance(Context context){
		if(coolWeatherDB==null){
			coolWeatherDB = new CoolWeatherDB(context);
		}
		return coolWeatherDB;
	}
	
	/**
	 * ½«ProvinceÊµÀý´æ´¢µ½Êý¾Ý¿â
	 */
	public void saveProvince(Province province){
		if(province!=null){
			ContentValues values = new ContentValues();
			values.put("province_name", province.getProvinceName());
			values.put("province_code", province.getProvinceCode());
			db.insert("Province", null, values);
		}
	}
	
	/**
	 * ´ÓÊý¾Ý¿âÖÐ¶ÁÈ¡Ê¡·ÝÐÅÏ¢
	 */
	public List<Province> loadProvinces(){
		List<Province> list = new ArrayList<Province>();
		Cursor cursor = db.query("Province", null, null, null, null, null, null);
		while(cursor.moveToNext()){
			Province province = new Province();
			province.setId(cursor.getInt(cursor.getColumnIndex("id")));
			province.setProvinceName(cursor.getString(cursor.getColumnIndex("province_name")));
			province.setProvinceCode(cursor.getString(cursor.getColumnIndex("province_code")));
			list.add(province);
		}
		if(cursor!=null){
			cursor.close();
		}
		return list;
	}
	
	/**
	 * ½«CityÊµÀý´æ´¢µ½Êý¾Ý¿â
	 */
	public void saveCity(City city){
		if(city!=null){
			ContentValues values = new ContentValues();
			values.put("city_name", city.getCityName());
			values.put("city_code", city.getCityCode());
			values.put("province_id", city.getProvinceId());
			db.insert("City", null, values);
		}
	}
	
	/**
	 * ¶ÁÈ¡Ä³¸öÊ¡·ÝµÄËùÓÐ³ÇÊÐÐÅÏ¢
	 */
	public List<City> loadCities(int provinceId){
		List<City> list = new ArrayList<City>();
		Cursor cursor = db.query("City", null, "province_id=?", new String[]{String.valueOf(provinceId)},
									null, null, null);
		while(cursor.moveToNext()){
			City city = new City();
			city.setId(cursor.getInt(cursor.getColumnIndex("id")));
			city.setCityName(cursor.getString(cursor.getColumnIndex("city_name")));
			city.setCityCode(cursor.getString(cursor.getColumnIndex("city_code")));
			city.setProvinceId(provinceId);
			list.add(city);
		}
		if(cursor!=null){
			cursor.close();
		}
		return list;
	}
	
}
