public class CongressmanDao extends Dao {
	private static final boolean EMPTY = true;
	private static final boolean NOT_EMPTY = false;
	
	private static CongressmanDao instance;
	private static String tableName = "CONGRESSMAN";
	
	private static String tableColumns[ ] = { "ID_CONGRESSMAN", "ID_UPDATE",
	        "NAME_CONGRESSMAN", "PARTY", "UF_CONGRESSMAN",
	        "TOTAL_SPENT_CONGRESSMAN", "STATUS_CONGRESSMAN",
	        "PHOTO_CONGRESSMAN", "RANKING_CONGRESSMAN" };
	
	private CongressmanDao( Context context ) {
		CongressmanDao.database = new DatabaseHelper( context );
	}
	
	/**
	 * Return the unique instance of CongressmanDao active in the project.
	 * <p>
	 * 
	 * @return The unique instance of CongressmanDao.
	 */
	public static CongressmanDao getInstance( Context context ) {
		if( CongressmanDao.instance != null ) {
			/* !Nothing To Do. */
			
		} else {
			CongressmanDao.instance = new CongressmanDao( context );
		}
		
		return CongressmanDao.instance;
	}
	
	/**
	 * Checks if database is empty.
	 */
	public boolean checkEmptyLocalDb() {
		sqliteDatabase = database.getReadableDatabase();
		
		String query = "SELECT  1 FROM " + tableName;
		
		Cursor cursor = sqliteDatabase.rawQuery( query, null );
		
		boolean isEmpty = NOT_EMPTY;
		
		if( cursor != null ) {
			
			if( cursor.getCount() <= 0 ) {
				cursor.moveToFirst();
				
				isEmpty = EMPTY;
				
			} else {
				/* ! Nothing To Do */
			}
			
		} else {
			
			isEmpty = EMPTY;
		}
		
		return isEmpty;
	}
	
	/**
	 * Checks database version.
	 */
	public boolean checkDbVersion(int remoteVersion) {
		sqliteDatabase = database.getReadableDatabase();
		
		String query = "SELECT * FROM VERSION";
		
		Cursor cursor = sqliteDatabase.rawQuery( query, null );
		cursor.moveToFirst();
		int currentVersion = cursor.getInt( cursor.getColumnIndex("NUM_VERSION") );
		
		boolean isLastVersion = currentVersion < remoteVersion;
		
		return isLastVersion;
	}
	
	/**
	 * Inserts in the database a version of remote 
	 * database.
	 * 
	 * @param int version of remote database.
	 * 
	 * @return Result if the operation was successful or not. 
	 */
	public boolean insertDbVersion( int version ) {
	   
	    boolean result = false;
    
		sqliteDatabase = database.getWritableDatabase();
		
		sqliteDatabase.delete( "VERSION",null, null);
		
		ContentValues content = new ContentValues();
		
		content.put( "NUM_VERSION", version );
		
		result = (insertAndClose( sqliteDatabase, "VERSION", content ) > 0 );
	
		return result;
	}
	
	/**
	 * Up
	 * 
	 * @param congressman
	 * @return
	 * @throws NullCongressmanException
	 */
	public boolean setFollowedCongressman( Congressman congressman )
	        throws NullCongressmanException {
		
		if( congressman != null ) {
			sqliteDatabase = database.getWritableDatabase();
			
			ContentValues content = new ContentValues();
			content.put( "STATUS_CONGRESSMAN", congressman.isStatusCogressman() );
			
			boolean result = ( sqliteDatabase.update( tableName, content,
			        "ID_CONGRESSMAN=?",
			        new String[] { congressman.getIdCongressman() + "" } ) > 0 );
			
			//sqliteDatabase.close();
			
			return result;
			
		} else {
			throw new NullCongressmanException();
		}
	}
	
	/**
	 * Inserts in the database a list of congressman.
	 * 
	 * @param congressmanList
	 *            List of Congressman to be inserted.
	 * 
	 * @return Result if the operation was successful or not.
	 * @throws NullCongressmanException 
	 */
	public boolean insertAllCongressman( List<Congressman> congressmanList ) 
	        throws NullCongressmanException {
		Iterator<Congressman> index = congressmanList.iterator();
		
		boolean result = true;
		
		while( index.hasNext() ) {
			result = insertCongressman( index.next() );
		}
		
		return result;
	}
	
	public boolean deleteAllCongressman() throws NullCongressmanException,
	    DatabaseInvalidOperationException {
		Iterator<Congressman> index = this.getAll(Order.RANKING).iterator();
		
		boolean result = false;
		boolean isEmptyDB = checkEmptyLocalDb();
		
		if( !isEmptyDB ) {
    		while( index.hasNext() ) {
    			result = deleteCongressman( index.next() );
    		}
		} else {
		     throw new DatabaseInvalidOperationException();
		}
		
		return result;
	}
	
	/**
	 * Retrieves all congressman contained in the database.
	 * 
	 * @return List of all congressman contained in the database.
	 */
	public List<Congressman> getAll(Order order) {
		
		sqliteDatabase = database.getReadableDatabase();
		
		String query = "SELECT * FROM " + tableName
		        + " ORDER BY "+ order.getOrderName() + " ASC";
		
		Cursor cursor = sqliteDatabase.rawQuery( query, null );
		
		List<Congressman> listParlamentares = new ArrayList<Congressman>();
		
		while( cursor.moveToNext() ) {
			
			Congressman congressman = new Congressman();
			
			congressman.setIdCongressman( cursor.getInt( cursor
			        .getColumnIndex( "ID_CONGRESSMAN" ) ) );
			
			congressman.setNameCongressman( cursor.getString( cursor
			        .getColumnIndex( "NAME_CONGRESSMAN" ) ) );
			
			congressman
			        .setStatusCogressman( convertStringToBool( cursor
			                .getString( cursor
			                        .getColumnIndex( "STATUS_CONGRESSMAN" ) ) ) );
			
			congressman.setPartyCongressman( cursor.getString( cursor
			        .getColumnIndex( "PARTY" ) ) );
			
			congressman.setUfCongressman( cursor.getString( cursor
			        .getColumnIndex( "UF_CONGRESSMAN" ) ) );
			
			congressman.setTotalSpentCongressman( cursor.getDouble( cursor
			        .getColumnIndex( "TOTAL_SPENT_CONGRESSMAN" ) ) );
			
			congressman.setRankingCongressman( cursor.getInt( cursor
			        .getColumnIndex( "RANKING_CONGRESSMAN" ) ) );
			
			congressman.setIdUpdateCongressman( cursor.getInt( cursor
			        .getColumnIndex( "ID_UPDATE" ) ) );
			
			listParlamentares.add( congressman );
		}
		
		//sqliteDatabase.close();
		
		return listParlamentares;
	}
	
	/**
	 * Retrieves a congressman contained in the database, based on pass name.
	 * <p>
	 * 
	 * @param congressmanName
	 *            The name of the congressman sought.
	 *            <p>
	 * @return A congressman sought.
	 * @throws DatabaseInvalidOperationException 
	 */
	public List<Congressman> selectCongressmanByName( String congressmanName ) {
	    List<Congressman> listCongressmen = new ArrayList<Congressman>();
		
		sqliteDatabase = database.getReadableDatabase();
		
		String[] whereArgs = { congressmanName };
		
		String query = "SELECT * FROM " + tableName
		        + " WHERE NAME_CONGRESSMAN = ?";

		Cursor cursor = sqliteDatabase.rawQuery( query, whereArgs );
		
		while( cursor.moveToNext() ) {
			
			Congressman congressman = new Congressman();
			
			congressman.setIdCongressman( cursor.getInt( cursor
			        .getColumnIndex( "ID_CONGRESSMAN" ) ) );
			
			congressman.setNameCongressman( cursor.getString( cursor
			        .getColumnIndex( "NAME_CONGRESSMAN" ) ) );
			
			congressman
			        .setStatusCogressman( Boolean.parseBoolean( cursor
			                .getString( cursor
			                        .getColumnIndex( "STATUS_CONGRESSMAN" ) ) ) );
			
			congressman.setPartyCongressman( cursor.getString( cursor
			        .getColumnIndex( "PARTY" ) ) );
			
			congressman.setUfCongressman( cursor.getString( cursor
			        .getColumnIndex( "UF_CONGRESSMAN" ) ) );
			
			congressman.setTotalSpentCongressman( cursor.getDouble( cursor
			        .getColumnIndex( "TOTAL_SPENT_CONGRESSMAN" ) ) );
			
			congressman.setRankingCongressman( cursor.getInt( cursor
			        .getColumnIndex( "RANKING_CONGRESSMAN" ) ) );
			
			congressman.setIdUpdateCongressman( cursor.getInt( cursor
			        .getColumnIndex( "ID_UPDATE" ) ) );
			
			listCongressmen.add( congressman );
		}
	
		//sqliteDatabase.close();
		
		return listCongressmen;
	}
	
	/**
	 * Retrieves all followed congressman. 
	 * <p>
	 * 
	 * @return All followed congressman.
	 * @throws DatabaseInvalidOperationException 
	 */
	public List<Congressman> getFollowedCongressman() {
	    List<Congressman> listFollowedCongressmen = new ArrayList<Congressman>();
		
		sqliteDatabase = database.getReadableDatabase();
		
		String query = "SELECT * FROM " + tableName
		        + " WHERE STATUS_CONGRESSMAN = 1";

		Cursor cursor = sqliteDatabase.rawQuery( query, null );
		
		while( cursor.moveToNext() ) {
			
			Congressman congressman = new Congressman();
			
			congressman.setIdCongressman( cursor.getInt( cursor
			        .getColumnIndex( "ID_CONGRESSMAN" ) ) );
			
			congressman.setNameCongressman( cursor.getString( cursor
			        .getColumnIndex( "NAME_CONGRESSMAN" ) ) );
			
			congressman
			        .setStatusCogressman( Boolean.parseBoolean( cursor
			                .getString( cursor
			                        .getColumnIndex( "STATUS_CONGRESSMAN" ) ) ) );
			
			congressman.setPartyCongressman( cursor.getString( cursor
			        .getColumnIndex( "PARTY" ) ) );
			
			congressman.setUfCongressman( cursor.getString( cursor
			        .getColumnIndex( "UF_CONGRESSMAN" ) ) );
			
			congressman.setTotalSpentCongressman( cursor.getDouble( cursor
			        .getColumnIndex( "TOTAL_SPENT_CONGRESSMAN" ) ) );
			
			congressman.setRankingCongressman( cursor.getInt( cursor
			        .getColumnIndex( "RANKING_CONGRESSMAN" ) ) );
			
			congressman.setIdUpdateCongressman( cursor.getInt( cursor
			        .getColumnIndex( "ID_UPDATE" ) ) );
			
			listFollowedCongressmen.add( congressman );
		}
	
		sqliteDatabase.close();
		
		return listFollowedCongressmen;
	}
	
	/* TODO: JAVADOC. */
	/* TODO: Unit Test. */
	public boolean checkCongressmanExist( int idCongressman ) {
	    List<Congressman> congressmanList = this.getAll(Order.RANKING);
	    
	    boolean result = false;
	    
	    for( Congressman congressman : congressmanList ) {
	        int idCurrentCongressman = congressman.getIdCongressman();
	        
	        if( idCongressman == idCurrentCongressman ) {
	            result = true;
	        } else {
	            /*! Nothing To Do. */
	        }
	    }
	    
	    return result;
	}
	
	private static boolean convertStringToBool( String string ) {
		if( string.equals( "1" ) )
			return true;
		if( string.equals( "0" ) )
			return false;
		throw new IllegalArgumentException( string
		        + " is not a bool. Only 1 and 0 are." );
	}
	
	/**
	 * Inserts in the database a congressman.
	 * 
	 * @param congressman
	 *            Congressman to be inserted.
	 * 
	 * @return Result if the operation was successful or not.
	 * @throws NullCongressmanException 
	 */
	private boolean insertCongressman( Congressman congressman ) 
	        throws NullCongressmanException {
	    boolean result = false;
	    
	    if( congressman != null ) {
    		sqliteDatabase = database.getWritableDatabase();
    		
    		ContentValues content = new ContentValues();
    		
    		content.put( tableColumns[ 0 ], congressman.getIdCongressman() );
    		content.put( tableColumns[ 1 ], congressman.
    		        getIdUpdateCongressman() );
    		content.put( tableColumns[ 2 ], congressman.getNameCongressman() );
    		content.put( tableColumns[ 3 ], congressman.getPartyCongressman() );
    		content.put( tableColumns[ 4 ], congressman.getUfCongressman() );
    		content.put( tableColumns[ 5 ], congressman.
    		        getTotalSpentCongressman() );
    		content.put( tableColumns[ 6 ], congressman.isStatusCogressman() );
    		content.put( tableColumns[ 7 ], congressman.getPhotoCongressman() );
    		content.put( tableColumns[ 8 ], congressman.
    		        getRankingCongressman() );
    		
    		result = ( 
    		        insertAndClose( sqliteDatabase, tableName, content ) > 0 );
	    } else {
	        throw new NullCongressmanException();
	    }
		
		return result;
	}
	
	private boolean deleteCongressman( Congressman congressman )
	        throws NullCongressmanException {
		
		if( congressman != null ) {
			sqliteDatabase = database.getWritableDatabase();
			
			boolean result = ( sqliteDatabase.delete( tableName,
			        "ID_CONGRESSMAN=?",
			        new String[] { congressman.getIdCongressman() + "" } ) > 0 );
			
		//	sqliteDatabase.close();
			
			return result;
		} else {
			throw new NullCongressmanException();
		}
	}
} public class JsonHelper {
	
	private static List<Congressman> congressmanList = new ArrayList<Congressman>();
	
	/**
	 * This server response to produce and return a list of Congressman.
	 * 
	 * @param jsonCongressmanList
	 *            Representation of the JSON of Congressman list.
	 * 
	 * @return List of Congressman
	 * 
	 * @throws NullCongressmanException
	 * @throws JSONException
	 */
	public static int versionFromJSON(
	        String jsonVersion ) throws JSONException {
		int remoteVersion;
		JSONArray jArray = new JSONArray( jsonVersion );
		
		remoteVersion = jArray.getJSONObject(0).getJSONObject( "fields" )
			        .getInt( "versaoupdate" );
		Log.i("VERSAO: ",""+remoteVersion);
		return remoteVersion;
	}
	
	/**
	 * This server response to produce and return a list of Congressman.
	 * 
	 * @param jsonCongressmanList
	 *            Representation of the JSON of Congressman list.
	 * 
	 * @return List of Congressman
	 * 
	 * @throws NullCongressmanException
	 * @throws JSONException
	 */
	public static List<Congressman> listCongressmanFromJSON(
	        String jsonCongressmanList ) throws NullCongressmanException,
	        JSONException {
		
		JSONArray jArray = new JSONArray( jsonCongressmanList );
		
		try {
			Congressman congressman = null;
			
			for( int index = 0; index < jArray.length(); index++ ) {
				
				congressman = new Congressman();

				congressman.setIdCongressman( jArray.getJSONObject( index )
				        .getInt( "pk" ) );
				
				congressman.setTotalSpentCongressman( jArray
				        .getJSONObject( index ).getJSONObject( "fields" )
				        .getDouble( "valor" ) );
				
				congressman.setRankingCongressman( jArray.getJSONObject( index )
				        .getJSONObject( "fields" ).getInt( "ranking" ) );
				
				congressman
				        .setUfCongressman( jArray.getJSONObject( index )
				                .getJSONObject( "fields" )
				                .getString( "ufparlamentar" ) );
				
				congressman.setPartyCongressman( jArray.getJSONObject( index )
				        .getJSONObject( "fields" )
				        .getString( "partidoparlamentar" ) );
				
				congressman.setNameCongressman( jArray.getJSONObject( index )
				        .getJSONObject( "fields" )
				        .getString( "nomeparlamentar" ) );
				
				congressmanList.add( congressman );
			}
		
		} catch( NullPointerException npe ) {
			throw new NullCongressmanException();
		}
		
		return congressmanList;
	}
	/**
	 * This server response to produce and return a list of Quotas.
	 * <p>
	 * 
	 * @param jsonQuotaByIdCongressmanList
	 *            Representation of the JSON of Quotas list.
	 *            <p>
	 * @return List of Quotas
	 *         <p>
	 * @throws NullCongressmanException
	 * @throws JSONException
	 */
	public static List<Quota> listQuotaByIdCongressmanFromJSON(
	        String jsonQuotaByIdCongressmanList )
	        throws NullCongressmanException, JSONException {
		
		List<Quota> quotaList = new ArrayList<Quota>();
		
		Quota quota;
		JSONArray jArray = new JSONArray( jsonQuotaByIdCongressmanList );
		
		try {
			
			for( int index = 0; index < jArray.length(); index++ ) {
				quota = new Quota();
				
				quota.setIdQuota( jArray.getJSONObject( index ).getInt( "pk" ) );
				
				quota.setIdUpdateQuota( jArray.getJSONObject( index )
				        .getJSONObject( "fields" ).getInt( "versaoupdate" ) );
				
				quota.setYearReferenceQuota( jArray.getJSONObject( index )
				        .getJSONObject( "fields" ).getInt( "ano" ) );
				
				quota.setValueQuota( jArray.getJSONObject( index )
				        .getJSONObject( "fields" ).getDouble( "valor" ) );
				
				quota.setIdCongressmanQuota( jArray.getJSONObject( index )
				        .getJSONObject( "fields" ).getInt( "idparlamentar" ) );
				
				quota.setTypeQuotaByNumber( jArray.getJSONObject( index )
				        .getJSONObject( "fields" ).getInt( "numsubcota" ) );
				
				quota.setDescriptionQuota( jArray.getJSONObject( index )
				        .getJSONObject( "fields" ).getString( "descricao" ) );
				
				quota.setTypeMonthByNumber( jArray.getJSONObject( index )
				        .getJSONObject( "fields" ).getInt( "mes" ) );
				
				quotaList.add( quota );
			}
			
		} catch( NullPointerException npe ) {
			throw new NullCongressmanException();
		}
		
		return quotaList;
	}
	
	/**
	 * This server response to produce and return a list of Statistics.
	 * <p>
	 * 
	 * @param jsonStatisticList
	 *            Representation of the JSON of Quotas list.
	 *            <p>
	 * @return List of Quotas
	 *         <p>
	 * @throws JSONException
	 */
	public static List<Statistic> listStatisticsFromJSON(
	        String jsonStatisticList )
	        throws NullCongressmanException, JSONException {
		
		List<Statistic> statisticList = new ArrayList<Statistic>();
		
		Statistic statistic;
		JSONArray jArray = new JSONArray( jsonStatisticList );
		
		try {
			for( int index = 0; index < jArray.length(); index++ ) {
				statistic = new Statistic();
				
				statistic.setIdStatistic(index+1);
				/*
				 * some statistics does not have referenced month
				 * */
				int month;
				try{
					month = jArray.getJSONObject( index ).getInt( "mes" );
				}catch(JSONException e) {
					month = 0;
				}
				statistic.setMonthByNumber(month);
				
				statistic.setSubquotaByNumber(jArray.getJSONObject(index)
						.getInt( "numsubcota"));
				
				/*
				 * some statistics does not have referenced year
				 * */
				int year;
				try{
					year = jArray.getJSONObject( index ).getInt( "ano" );
				}catch(JSONException e) {
					year = 0;
				}
				statistic.setYear(year);
				
				statistic.setAverage( jArray.getJSONObject( index )
				        .getDouble( "valor_medio" ) );
				
				statistic.setMaxValue( jArray.getJSONObject( index )
				        .getDouble( "valor_maximo" ) );
				
				/*
				 * some statistics does not have referenced std deviation
				 * */
				double stdDevition;
				try{
					stdDevition = jArray.getJSONObject( index )
				        .getDouble( "desvio_padrao" );
				}catch(JSONException e) {
					stdDevition = 0.0;
				}
				statistic.setStdDeviation(stdDevition);
				
				statisticList.add( statistic );
			}
		} catch( NullPointerException npe ) {
			throw new NullCongressmanException();
		}
		
		return statisticList;
	}
} public class HttpConnection {
	
	/**
	 * Creates an object handler that encapsulates the process of generating a
	 * response object from a HttpResponse.
	 */
	public final static ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
		
		/**
		 * Processes an HttpResponse and returns some value corresponding to that
		 * response.
		 * 
		 * @param response
		 *           The response to process.
		 * 
		 * @return The response sent by the server.
		 * 
		 * @throws IOException
		 */
		public String handleResponse( HttpResponse response ) throws IOException {
			
			HttpEntity entity = response.getEntity();
			String result = null;
			
			BufferedReader buffer = new BufferedReader( new InputStreamReader(
			      entity.getContent() ) );
			
			StringBuilder builder = new StringBuilder();
			String line = null;
			
			while( ( line = buffer.readLine() ) != null ) {
				
				builder.append( line + "\n" );
			}
			
			buffer.close();
			result = builder.toString();
			
			return result;
		}
	};
	
	/**
	 * Returns the ResponseHandler generated by HttpConnection to handle server
	 * responses.
	 * 
	 * @return The ResponseHandler created.
	 */
	public synchronized static ResponseHandler<String> getResponseHandler() {
		return responseHandler;
	}
	
	/**
	 * Use responseHandler created to request the requested through a URL.
	 * 
	 * @param response
	 *           The response to process.
	 * 
	 * @param url
	 *           requested URL.
	 * 
	 * @return JSON is that the server response.
	 * 
	 * @throws ConnectionFailedException
	 */
	public static String request( ResponseHandler<String> response, String url )
	      throws ConnectionFailedException {
		
		try {
			
			DefaultHttpClient client = new DefaultHttpClient();
			HttpGet http = new HttpGet( url );
			
			String json = new String( client.execute( http, response ).getBytes(
			      "ISO-8859-1" ), "UTF-8" );
			
			return json;
			
		} catch( ClientProtocolException e ) {
			throw new ConnectionFailedException();
			
		} catch( IOException ioe ) {
			throw new ConnectionFailedException();
		}
	}
} public enum Order {
	RANKING( 0, "RANKING_CONGRESSMAN" ),
	ALPHABETIC( 1, "NAME_CONGRESSMAN" ),
	STATE( 2, "UF_CONGRESSMAN" ),
	PARTY( 3, "PARTY" );
	
	private int valueOrder;
	private String representativeName;
	
	Order( int value, String name ) {
		this.valueOrder = value;
		this.representativeName = name;
	}
	
	/**
	 * Return the numerical value of the ordenation.
	 * 
	 * @return The numerical value of the ordenation.
	 */
	public int getValueOrder() {
		return valueOrder;
	}
	
	/**
	 * Return a name that represent the ordenation.
	 * 
	 * @return The name that represent this ordenation.
	 */
	public String getOrderName() {
		return representativeName; 
	}

} public class ConnectionFailedException extends Exception {
	private static final long serialVersionUID = 834455534735333354L;
	
	public ConnectionFailedException() {
		/*! Empty Constructor. */
	}
	
	public ConnectionFailedException( String message ) {
		super( message );
	}
} public class DatabaseInvalidOperationException extends Exception {
    private static final long serialVersionUID = 380307236047507820L;
} public class NullCongressmanException extends Exception {
	private static final long serialVersionUID = -652180129137381807L;
	
	public NullCongressmanException() {
		/*! Empty Constructor. */
	}
	
	public NullCongressmanException( String message ) {
		super( message );
	}
} public class NullQuotaException extends Exception {
    private static final long serialVersionUID = -1145318178523488779L;
} public class Congressman {
	static final boolean FOLLOWED = true;
	static final boolean NOT_FOLLOWED = false;
	
	protected int id = 0;
	protected int idUpdateCongressman = 0;
	protected boolean statusCogressman = NOT_FOLLOWED;
	protected byte[] photoCongressman = null;
	
	protected String nameCongressman = "";
	protected String partyCongressman = "";
	protected String ufCongressman = "";
	protected int ranking = 0;
	protected List<Quota> quotasCongressman = null;
	protected double totalSpentCongressman = 0;
	protected String typeCongressman = "";
	
	public String getTypeCongressman() {
		return typeCongressman;
	}
	
	public void setTypeCongressman( String typeCongressman ) {
		this.typeCongressman = typeCongressman;	
	}
	
	public int getIdCongressman() {
		return id;
	}
	
	public void setIdCongressman( int idCongressman ) {
		this.id = idCongressman;
	}
	
	public int getIdUpdateCongressman() {
		return idUpdateCongressman;
	}
	
	public void setIdUpdateCongressman( int idUpdateCongressman ) {
		this.idUpdateCongressman = idUpdateCongressman;
	}
	
	public boolean isStatusCogressman() {
		return statusCogressman;
	}
	
	public void setStatusCogressman( boolean statusCogressman ) {
		this.statusCogressman = statusCogressman;
	}
	
	public byte[] getPhotoCongressman() {
		return photoCongressman;
	}
	
	public void setPhotoCongressman( byte[] photoCongressman ) {
		this.photoCongressman = photoCongressman;
	}
	
	public String getNameCongressman() {
		return nameCongressman;
	}
	
	public void setNameCongressman( String nameCongressman ) {
		this.nameCongressman = nameCongressman;
	}
	
	public String getPartyCongressman() {
		return partyCongressman;
	}
	
	public void setPartyCongressman( String partyCongressman ) {
		this.partyCongressman = partyCongressman;
	}
	
	public String getUfCongressman() {
		return ufCongressman;
	}
	
	public void setUfCongressman( String ufCongressman ) {
		this.ufCongressman = ufCongressman;
	}
	
	public List<Quota> getQuotasCongressman() {
		return quotasCongressman;
	}
	
	public void setQuotasCongressman( List<Quota> quotasCongressman ) {
		this.quotasCongressman = quotasCongressman;
	}
	
	public double getTotalSpentCongressman() {
		return totalSpentCongressman;
	}
	
	public void setTotalSpentCongressman( double totalSpentCongressman ) {
		this.totalSpentCongressman = totalSpentCongressman;
	}
	
	public int getRankingCongressman() {
		return ranking;
	}
	
	public void setRankingCongressman( int rankingCongressman ) {
		this.ranking = rankingCongressman;
	}
} public class Quota {
	private int idQuota = 0;
	private int idCongressman = 0;
	private int idUpdateQuota = 0;
	private SubQuota typeQuota = SubQuota.WITHOUT_TYPE;
	
	private Month monthReferenceQuota = Month.WITHOUT_MONTH;
	private int yearReferenceQuota = 0;
	private String descriptionQuota = "";
	private double valueQuota = 0;
	
	private Statistic statisticQuota = null;
	
	public Quota( int id, int idCongressman, SubQuota subquota, double value ) {
		this.idQuota = id;
		this.idCongressman = idCongressman;
		this.typeQuota = subquota;
		this.valueQuota = value;
	}
	
	public Quota(){};
	public int getIdQuota() {
		return idQuota;
	}
	
	public void setIdQuota( int idQuota ) {
		this.idQuota = idQuota;
	}
	
	public int getIdCongressmanQuota() {
		return idCongressman;
	}
	
	public void setIdCongressmanQuota( int idCongressmanQuota ) {
		this.idCongressman = idCongressmanQuota;
	}
	
	public int getIdUpdateQuota() {
		return idUpdateQuota;
	}
	
	public void setIdUpdateQuota( int idUpdateQuota ) {
		this.idUpdateQuota = idUpdateQuota;
	}
	
	public SubQuota getTypeQuota() {
		return typeQuota;
	}
	
	private void setTypeQuota( SubQuota typeQuota ) {
		this.typeQuota = typeQuota;
	}
	
	public void setTypeQuotaByNumber (int type){
		
		switch(type){
				
		case 1:
			setTypeQuota(SubQuota.OFFICE);
			break;
		case 3:
			setTypeQuota(SubQuota.FUEL);
			break;
		case 4:
			setTypeQuota(SubQuota.TECHNICAL_WORK_AND_CONSULTING);
			break;
		case 5:
			setTypeQuota(SubQuota.DISCLOSURE_PARLIAMENTARY_ACTIVITY);
			break;
		case 8:
			setTypeQuota(SubQuota.SAFETY);
			break;
		case 9:
			setTypeQuota(SubQuota.ISSUANCE_OF_AIR_TICKETS);
			break;
		case 10:
			setTypeQuota(SubQuota.TELEPHONY);
			break;
		case 11:
			setTypeQuota(SubQuota.POSTAL_SERVICES);
			break;
		case 12:
			setTypeQuota(SubQuota.SIGNATURE_OF_PUBLICATION);
			break;
		case 13:
			setTypeQuota(SubQuota.ALIMENTATION);
			break;
		case 14:
			setTypeQuota(SubQuota.ACCOMMODATION);
			break;
		case 15:
			setTypeQuota(SubQuota.LEASE_OF_VEHICLES);
			break;
		case 119:
			setTypeQuota(SubQuota.AIR_FREIGHT);
			break;
		default:
			setTypeQuota(SubQuota.WITHOUT_TYPE);
		}
	}
	
public void setTypeMonthByNumber (int type){
		
		switch(type){
				
		case 1:
			setMonthReferenceQuota(Month.JANUARY);
			break;
		case 2:
			setMonthReferenceQuota(Month.FEBRUARY);
			break;
		case 3:
			setMonthReferenceQuota(Month.MARCH);
			break;
		case 4:
			setMonthReferenceQuota(Month.APRIL);
			break;
		case 5:
			setMonthReferenceQuota(Month.MAY);
			break;
		case 6:
			setMonthReferenceQuota(Month.JUNE);
			break;
		case 7:
			setMonthReferenceQuota(Month.JULY);
			break;
		case 8:
			setMonthReferenceQuota(Month.AUGUST);
			break;
		case 9:
			setMonthReferenceQuota(Month.SEPTEMBER);
			break;
		case 10:
			setMonthReferenceQuota(Month.OCTOBER);
			break;
		case 11:
			setMonthReferenceQuota(Month.NOVEMBER);
			break;
		case 12:
			setMonthReferenceQuota(Month.DECEMBER);
			break;
		default:
			//nothing to do
			
			
		}
	}
	
	public Month getMonthReferenceQuota() {
		return monthReferenceQuota;
	}
	
	public void setMonthReferenceQuota( Month monthReferenceQuota ) {
		this.monthReferenceQuota = monthReferenceQuota;
	}
	
	public int getYearReferenceQuota() {
		return yearReferenceQuota;
	}
	
	public void setYearReferenceQuota( int yearReferenceQuota ) {
		this.yearReferenceQuota = yearReferenceQuota;
	}
	
	public String getDescriptionQuota() {
		return descriptionQuota;
	}
	
	public void setDescriptionQuota( String descriptionQuota ) {
		this.descriptionQuota = descriptionQuota;
	}
	
	public double getValueQuota() {
		return valueQuota;
	}
	
	public void setValueQuota( double valueQuota ) {
		this.valueQuota = valueQuota;
	}

	public Statistic getStatisticQuota() {
		return statisticQuota;
	}

	public void setStatisticQuota( Statistic statisticQuota ) {
		this.statisticQuota = statisticQuota;
	}
}

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.http.client.ResponseHandler;
import org.json.JSONException;
import android.content.Context;
import android.util.Log;
import br.com.visualize.akan.api.dao.CongressmanDao;
import br.com.visualize.akan.api.helper.JsonHelper;
import br.com.visualize.akan.api.request.HttpConnection;
import br.com.visualize.akan.domain.enumeration.Order;
import br.com.visualize.akan.domain.exception.ConnectionFailedException;
import br.com.visualize.akan.domain.exception.DatabaseInvalidOperationException;
import br.com.visualize.akan.domain.exception.NullCongressmanException;
import br.com.visualize.akan.domain.exception.NullQuotaException;
import br.com.visualize.akan.domain.model.Congressman;
import br.com.visualize.akan.domain.model.Quota;
/*
 * File: CongressmanController.java Purpose: Brings the implementation of class
 * CongressmanController.
 */
package br.com.visualize.akan.domain.controller;





/**
 * Serves to define the methods that are responsible for generating actions,
 * calculate results and everything that is requested by layer 'View' referring
 * to Congressman.
 */
public class CongressmanController {
	
	private static CongressmanController instance = null;
	private static Congressman congressman;
	private static List<Congressman> congressmanList = new ArrayList<Congressman>();
	
	private Order order = Order.RANKING;
	
	private Map<String,String> partyFilters = new HashMap<String,String>();
	private Map<String,String> spentFilters = new HashMap<String,String>();
	private Map<String,String> stateFilters = new HashMap<String,String>();

	private boolean followedFilter = false;
	
	private UrlController urlController;
	private CongressmanDao congressmanDao;
	private QuotaController quotaController;
	
	private CongressmanController( Context context ) {
		congressmanDao = CongressmanDao.getInstance( context );
		urlController = UrlController.getInstance( context );
		quotaController = QuotaController.getInstance( context );
		
		spentFilters.put("0","0");
	}
	
	/**
	 * Return the unique instance of CongressmanController active in the
	 * project.
	 * 
	 * @return The unique instance of CongressmanController.
	 */
	public static CongressmanController getInstance( Context context ) {
		if( instance == null ) {
			instance = new CongressmanController( context );
		} else {
			/* ! Nothing To Do. */
		}
		return instance;
	}
	
	/**
	 * Associates a congressman on CongressmanController.
	 * 
	 * @param congressman
	 *            Congressman to be associated
	 */
	public void setCongressman( Congressman congressman ) {
		CongressmanController.congressman = congressman;
	}
	
	/**
	 * Search the database all congressman and returns them as a list.
	 * 
	 * @param responseHandler
	 *            Handler of welcoming server responses
	 * 
	 * @return List of Congressman resulting from the server.
	 * 
	 * @throws Exception
	 */
	public List<Congressman> requestAllCongressman(
	        ResponseHandler<String> responseHandler ) 
	                throws NullCongressmanException, NullQuotaException, 
	                JSONException, ConnectionFailedException {