public class Define {
    public static boolean DEBUG = false;
    
	public static String APP_ID = "125";
	public static String APP_SECRET = "1c5224ad2961704a6076c0bda127003933828a16";
	public static String PIN = null;
	public static String REAL_TOKEN = null;
	public static int USER_ID = -1;
	public static String TOKEN_SECRET = null;
	public static String APP_SECTION = null;
	
	public static String CURRENCY_CODE = null;
	public static String COUNTRY_CODE = null;;
	public static String TIMEZONE = null;
	public static String LOCALE_LANGUAGE = null;
	
	// General Key and Shared Preference Key
	public static String SHARED_PREFERENCE = "SHARED_AUTH";
	public static String KEY_SHARED_PIN = "SHARED_PIN";
	public static String KEY_SHARED_TOKEN = "SHARED_TOKEN";
	public static String KEY_SHARED_TOKEN_SECRET = "SHARED_TOKEN_SECRET";
	public static String KEY_SHARED_USER_ID = "SHARED_USER_ID";
	public static String KEY_SHARED_SECTION_ID = "SHARED_SECTION_ID";
	public static String KEY_SHARED_USER_INFO = "SHARED_USER_INFO";
	
	public static String KEY_SHARED_CURRENCY_CODE = "SHARED_CURRENCY_CODE";
	public static String KEY_SHARED_COUNTRY_CODE = "SHARED_COUNTRY_CODE";
	public static String KEY_SHARED_TIMEZONE = "SHARED_TIMEZONE";
	public static String KEY_SHARED_LOCALE_LANGUAGE = "SHARED_LOCALE_LANG";
	
	// Response/Request Key
	public static final int RESPONSE_EXIT = 10;
	public static final int REQUEST_AUTH = 50;
	public static final int REQUEST_NORMAL = 51;
	
	//Message
	public static final int MSG_REQ_AUTH = 100;
	public static final int MSG_FAIL = 101;
	public static final int MSG_AUTH_DONE = 102;
	public static final int MSG_AUTH_TOTAL_DONE = 103;
	public static final int MSG_USER_SETTING_DONE = 104;
	public static final int MSG_SETTING_DONE = 105;
	
	public static final int RESULT_OK = 200;
	public static final int RESULT_NONE_RECORD = 204;
	public static final int RESULT_ERROR = 400;
	public static final int RESULT_INSUFFIENT_API = 402;
	
	public static final int MSG_API_OK = 1000;
	public static final int MSG_API_FAIL = 1003;
	public static final int MSG_API_FAIL_WITH_404 = 404;
		
	public static final int API_GET_SECTIONS = 2010;
	public static final int API_GET_MAIN = 2020;
	public static final int API_GET_BUDGET = 2030;
	public static final int API_GET_BALANCE = 2040;

    public static final int API_GET_ENTRIES_LATEST = 2060;
    public static final int API_GET_ENTRIES_INSERT = 2061;
    public static final int API_GET_ENTRIES_LATEST_ITEMS = 2062;
    public static final int API_GET_PL = 2070;
    public static final int API_GET_MOUNTAIN = 2080;
    public static final int API_GET_ENTRIES = 2090;
    public static final int API_GET_BILL = 2100;
    
    // Post It
    public static final int API_GET_POST_IT = 2110;
    public static final int API_POST_POSTIT = 2111;
    public static final int API_PUT_POSTIT = 2112;
    public static final int API_DELETE_POSTIT = 2113;
    
    // Board
    public static final int API_GET_BOARD = 2190;
    public static final int API_GET_BOARD_BASE = 2200;
    public static final int API_GET_BOARD_FREE = 2200;
    public static final int API_GET_BOARD_MONEY_TALK = 2201;
    public static final int API_GET_BOARD_COUNSELING = 2202;
    public static final int API_GET_BOARD_WHOOING = 2203;
    
    //Board Article
    public static final int API_GET_BOARD_ARTICLE = 2210;
    public static final int API_POST_BOARD_ARTICLE = 2211;
    public static final int API_PUT_BOARD_ARTICLE = 2212;
    public static final int API_DELETE_BOARD_ARTICLE = 2213;
    
    
    public static final int API_POST_BOARD_REPLY = 2220;
    public static final int API_PUT_BOARD_REPLY = 2221;
    public static final int API_DELETE_BOARD_REPLY = 2222;
    
    //Board Comment
    public static final int API_GET_BOARD_COMMENT = 2230;
    public static final int API_POST_BOARD_COMMENT = 2231;
    public static final int API_PUT_BOARD_COMMENT = 2232;
    public static final int API_DELETE_BOARD_COMMENT = 2233;

    // Account
    public static final int API_GET_ACCOUNTS = 2300;
    public static final int API_POST_ACCOUNTS = 2301;
    public static final int API_PUT_ACCOUNTS = 2302;
    public static final int API_DELETE_ACCOUNTS = 2303;
    public static final int API_GET_ACCOUNT_EXISTS_ENTRIES = 2304;    
    
    // user
    public static final int API_GET_USER_INFO = 3000;
    public static final int API_PUT_USER_INFO = 3001;
    
    // etc
    public static final int API_GET_FREQUENT_ITEM = 3010;
    
    
	public static Typeface ROBOFONT = null;
    
    
    //flags
    //If there is need to be refreshed by insert some transaction or something like that
    //set this flag true
    public static boolean NEED_TO_REFRESH = false;
    
    public static boolean SHOW_NO_API_INFORM = false;
    
    public static void gettingLoginInfo(Context context){
    	if(context == null){
    		return;
    	}
    	/*
        if(Define.DEBUG){
            Define.REAL_TOKEN = "9772ff8e2f751ddf1c5cf74b0d9b328f392a4b71";
            Define.PIN = "339599";
            Define.TOKEN_SECRET = "7776e79057bc222254da0b108555afd86e3b7d3c";
            Define.APP_SECTION = "s10550";
            Define.USER_ID = 8955;
            Define.CURRENCY_CODE = "KRW";
            Define.COUNTRY_CODE="KR";
            Define.LOCALE_LANGUAGE = "ko";
        }*/
    	SharedPreferences prefs = context.getSharedPreferences(Define.SHARED_PREFERENCE, Context.MODE_PRIVATE);
        Define.REAL_TOKEN = prefs.getString(Define.KEY_SHARED_TOKEN, null);
        Define.PIN = prefs.getString(Define.KEY_SHARED_PIN, null);
        Define.TOKEN_SECRET = prefs.getString(Define.KEY_SHARED_TOKEN_SECRET, null);
        Define.APP_SECTION = prefs.getString(Define.KEY_SHARED_SECTION_ID, null);
        Define.USER_ID = prefs.getInt(Define.KEY_SHARED_USER_ID, 0);
        Define.CURRENCY_CODE = prefs.getString(Define.KEY_SHARED_CURRENCY_CODE, "USD");
        Define.COUNTRY_CODE = prefs.getString(Define.KEY_SHARED_COUNTRY_CODE, "US");
        Define.LOCALE_LANGUAGE = prefs.getString(Define.KEY_SHARED_LOCALE_LANGUAGE, "en");
        Define.TIMEZONE = prefs.getString(Define.KEY_SHARED_TIMEZONE, null);
    }

} public class WhooingApplication extends Application {
    
    private static WhooingApplication sInstance;
    //using singleton
    private static DataRepository dataRepository = null;
    
    public static WhooingApplication getInstance(){
        return sInstance;
    }
    
    public synchronized DataRepository getRepo(){
        if(dataRepository == null){
            Log.d("wisedog", "DataRepository is just created");
            dataRepository = new DataRepository();
        }
        return dataRepository;
    }
    
    @Override
    public void onCreate() {
      super.onCreate();  
      sInstance = this;
      sInstance.initializeInstance();
    }

    private void initializeInstance() {
        dataRepository = new DataRepository();        
    }

} public class BbsListFragment extends ListFragment implements OnItemClickListener {
	public static final int BOARD_TYPE_FREE = 0;
	public static final int BOARD_TYPE_MONEY_TALK = 1;
	public static final int BOARD_TYPE_COUNSELING = 2;
	public static final int BOARD_TYPE_WHOOING = 3;

	/** Container to store BBS List data */
	protected ArrayList<BoardItem> mDataArray;
	/** Footer view of Listview*/
	protected View footerView;
	/** Adapter of this Listview*/
	protected BoardAdapter mAdapter;
	/** Page number to loading*/
	private int mPageNum = 1;
	/** Board type*/
	private int mBoardType = -1;
	
	private boolean isLoading = false;
	
    
	/**
	 * Get new fragment instance
	 * @param	b	bundle instance to set argument to this fragment
	 * */
    public static BbsListFragment newInstance(Bundle b){
    	BbsListFragment f = new BbsListFragment();
    	f.setArguments(b);
    	return f;
    }

    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mDataArray = new ArrayList<BoardItem>();
        mAdapter = new BoardAdapter(getActivity(), mDataArray);
        mBoardType = getArguments().getInt("board_type");
        setHasOptionsMenu(true);
    }

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		footerView = getActivity().getLayoutInflater().inflate(R.layout.footer, null, false);
		getListView().addFooterView(footerView, null, false);
        
		getListView().setOnScrollListener(new EndlessScrollListener(){

			@Override
			public void onLoadMore(int page, int totalItemsCount) {
		    	if(isLoading == false){
		    		getMore();
		    	}
			}
		});
		getListView().setOnItemClickListener(this);
		//getListView().removeFooterView(footerView);
		setListAdapter(mAdapter);
		super.onActivityCreated(savedInstanceState);
	}


	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		BoardItem item = (BoardItem)(getListView().getItemAtPosition(position));
		BbsArticleFragment f = new BbsArticleFragment();
    	f.setData(mBoardType, item);
        getActivity().getFragmentManager().beginTransaction()
        .addToBackStack(null)
        .replace(R.id.main_content, f)
        .commit();
	}
    
    
    @Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    	menu.clear();
    	inflater.inflate(R.menu.write_bbs_menus, menu);
		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getItemId() == R.id.menu_action_bbs_write){
			((MainFragmentActivity)getActivity()).addBbsWriteFragment(BbsWriteFragment.MODE_WRITE_ARTICLE, 
					null, null, 0, null, mBoardType);
		}
		return super.onOptionsItemSelected(item);
	}



	@SuppressLint("HandlerLeak")
	protected Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
        	isLoading = false;
            if(msg.what == Define.MSG_API_OK){
                if(msg.arg1 == Define.API_GET_BOARD){
                    mPageNum = mPageNum + 1;
                    JSONObject obj = (JSONObject)msg.obj;
                    try {
                        fillListItems(obj);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
            super.handleMessage(msg);
        }
        
    };
    
    /**
     * Fill list item with data from server
     * @param	obj		The data formatted in JSON
     * @throws	JSONException
     * */
    protected void fillListItems(JSONObject obj) throws JSONException{    	
        JSONArray array = obj.getJSONArray("results");
        int length = array.length();
        
        //Clear data for refresh
        if(mPageNum == 2 && !mDataArray.isEmpty()){
            mDataArray.clear();
        }
        
        for(int i = 0; i < length; i++){
            JSONObject entity = array.getJSONObject(i);
            int id = entity.getInt("bbs_id");
            String subject = entity.getString("subject");
            int commentNum = entity.getInt("comments");
            int hits = entity.getInt("hits");
            String contents = entity.getString("contents");
            int recommandation = entity.getInt("recommandation");
            long timestamp = entity.getLong("timestamp");
            
            JSONObject objWriter = entity.getJSONObject("writer");
            String userName = objWriter.getString("username");
            String userImage = objWriter.getString("image_url");
            int userId = objWriter.getInt("user_id");
            int userLevel = objWriter.getInt("level");
            
                    
            BoardItem item = new BoardItem(id, userName, commentNum, subject);
            item.hits = hits;
            item.contents = contents;
            item.recommandation = recommandation;
            item.userId = userId;
            item.userLevel = userLevel;
            item.userImage = userImage;
            item.timestamp = timestamp;
            item.category = entity.getString("category");
            
            mDataArray.add(item);
        }
        try{
        	getListView().removeFooterView(footerView);
        }
        catch(IllegalStateException e){
        	e.printStackTrace();
        	Toast.makeText(getActivity(), "Err- List#01", Toast.LENGTH_LONG).show();
        }
        mAdapter.notifyDataSetChanged();
    }

    /**
     * Get more list items
     * */
    public void getMore(){
    	isLoading = true;
    	getListView().addFooterView(footerView, null, false);
        Bundle b = new Bundle();
        b.putInt("board_type", mBoardType);
        b.putInt("page", mPageNum);
        b.putInt("limit", 18);
        
        JSONObject obj = WhooingApplication.getInstance().getRepo().getUserValue();
        String language = Define.LOCALE_LANGUAGE;
        try {
            language = obj.getString("language");
        } catch (JSONException e) {
            e.printStackTrace();
        } catch(NullPointerException e){
        	e.printStackTrace();
        	//TODO Get User Value when user value is null
        	return;
        }
        b.putString("language", language);
        ThreadRestAPI thread = new ThreadRestAPI(mHandler,
                Define.API_GET_BOARD, b);
        thread.start();
    }

} public class AccountsApi extends AbstractAPI {
    public static int TYPE_POST = 0;
    public static int TYPE_PUT = 1;
    
    /**
     * Delete accounts info
     * @param   appID       Application ID
     * @param   token       Token
     * @param   appKey      Application Key
     * @param   tokenSecret Secret key for token
     * @param   bundle      Bundle 
     * @return  Returns JSONObject for result, or null if it fails      
     * */
    public JSONObject deleteAccounts(String appSection, String appID, String token, 
            String appKey, String tokenSecret, Bundle bundle) {
        if(bundle == null){
            return null;
        }
        String accountId = bundle.getString("account_id");
        String accountType = bundle.getString("account_type");
        String entriesURL = "https://whooing.com/api/accounts/" + accountType + "/" +  accountId
                + "/" + appSection + ".json";
        JSONObject result = callApiDelete(entriesURL, appID, token, appKey, tokenSecret, appSection);
        
        return result;
    }
    
    public JSONObject existTransaction(String appSection, String appID, String token, 
            String appKey, String tokenSecret, Bundle bundle){
        if(bundle == null){
            return null;
        }
        String accountId = bundle.getString("account_id");
        String accountType = bundle.getString("account_type");
        
        if(accountId == null || accountType == null){
            return null;
        }
        String entriesURL = "https://whooing.com/api/accounts/" + accountType + "/"+ accountId + "/exists.json"
                +"?section_id=" +appSection;
        JSONObject result = callApi(entriesURL, appID, token, appKey, tokenSecret);
        return result;
    }

    /**
     * Put or Post accounts info. Put and post requires almost same parameters
     * @param   appID       Application ID
     * @param   token       Token
     * @param   appKey      Application Key
     * @param   tokenSecret Secret key for token
     * @param   bundle      Bundle 
     * @return  Returns     JSONObject for result, or null if it fails      
     * */
    public JSONObject postOrPutAccounts(int type, String appSection, String appID, String token, 
            String appKey, String tokenSecret, Bundle bundle) {
        if(bundle == null){
            return null;
        }
        
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        String accountType = null;
        AccountsEntity entity = bundle.getParcelable("account_entity");
        // from deactivate dialog 
        if(entity == null){
            accountType = bundle.getString("account_type");
        }
        else{   //from account modify dialog
            accountType = entity.accountType;
            nameValuePairs.add(new BasicNameValuePair("title", entity.title));
            nameValuePairs.add(new BasicNameValuePair("section_id", appSection));
            nameValuePairs.add(new BasicNameValuePair("type", entity.type));
            nameValuePairs.add(new BasicNameValuePair("open_date", String.valueOf(entity.open_date)));
            nameValuePairs.add(new BasicNameValuePair("category", entity.category));
            
            if(entity.memo != null){
                nameValuePairs.add(new BasicNameValuePair("memo", entity.memo));
            }
            
            if(entity.category.compareTo("creditcard") == 0){
                nameValuePairs.add(new BasicNameValuePair("opt_use_date", entity.opt_use_date));
                nameValuePairs.add(new BasicNameValuePair("opt_pay_date", String.valueOf(entity.opt_pay_date)));
                nameValuePairs.add(new BasicNameValuePair("opt_pay_account_id", entity.opt_pay_account_id));
                
            }else if(entity.category.compareTo("checkcard") == 0){
                nameValuePairs.add(new BasicNameValuePair("opt_pay_account_id", entity.opt_pay_account_id));
            }        
        }        
        
        String entriesURL = null;
        
        JSONObject result = null;
        if(type == TYPE_POST){
            entriesURL = "https://whooing.com/api/accounts/" + accountType + ".json";
            result = callRawApiPost(entriesURL, appID, token, appKey, tokenSecret, appSection, nameValuePairs);
        }else if(type == TYPE_PUT){
            if(entity == null){
                nameValuePairs.add(new BasicNameValuePair("is_close", bundle.getString("is_close")));
            }else{
                if(entity.close_date != 0){
                    nameValuePairs.add(new BasicNameValuePair("is_close", "y"));
                }
                else{
                    nameValuePairs.add(new BasicNameValuePair("is_close", "n"));
                }
            }
            
            nameValuePairs.add(new BasicNameValuePair("section_id", appSection));
            
            String accountId = bundle.getString("account_id");
            entriesURL =  "https://whooing.com/api/accounts/" + accountType + "/" + accountId + ".json";
            result = callApiPut(entriesURL, appID, token, appKey, tokenSecret, appSection, nameValuePairs);
        }
        return result;
    }
} public class BbsApi extends AbstractAPI{

	public JSONObject postBbsArticle(String appSection, String appID, String token, 
            String appKey, String tokenSecret, Bundle bundle){
	    if(bundle == null){
            return null;
        }
        String entriesURL = "https://whooing.com/api/bbs/" + getBoardType(bundle.getInt("board_type")) + ".json";
        
        String subject = bundle.getString("subject");
        String contents = bundle.getString("contents");
        
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("contents", contents));
        nameValuePairs.add(new BasicNameValuePair("subject", subject));
        
        JSONObject result = callRawApiPost(entriesURL, appID, token, appKey, tokenSecret, appSection, nameValuePairs);
        return result;
    }

    /**
     * @param appSection
     * @param appID
     * @param token
     * @param appKey
     * @param tokenSecret
     * @param bundle
     * @return
     */
    public JSONObject delBbsArticle(String appSection, String appID, String token, 
            String appKey, String tokenSecret, Bundle bundle) {
        if(bundle == null){
            return null;
        }
        String boardType = getBoardType(bundle.getInt("board_type"));
        String entriesURL = "https://whooing.com/api/bbs/" + boardType + "/" +  bundle.getInt("bbs_id") + ".json";
        JSONObject result = callApiDelete(entriesURL, appID, token, appKey, tokenSecret, appSection);
        return result;
    }
    
    /**
     * @param appSection
     * @param appID
     * @param token
     * @param appKey
     * @param tokenSecret
     * @param bundle
     * @return
     */
    public JSONObject delBbsReply(String appSection, String appID, String token, 
            String appKey, String tokenSecret, Bundle bundle) {
        if(bundle == null){
            return null;
        }
        String boardType = getBoardType(bundle.getInt("board_type"));
        String entriesURL = "https://whooing.com/api/bbs/" + boardType + "/" +  bundle.getInt("bbs_id") 
                + "/" + bundle.getString("comment_id") + ".json";
        JSONObject result = callApiDelete(entriesURL, appID, token, appKey, tokenSecret, appSection);
        return result;
    }
    

    /**
     * @param aPP_SECTION
     * @param aPP_ID
     * @param rEAL_TOKEN
     * @param aPP_SECRET
     * @param tOKEN_SECRET
     * @param mBundle
     * @return
     */
    public JSONObject putBbsArticle(String appSection, String appID, String token, 
            String appKey, String tokenSecret, Bundle bundle) {
    	 if(bundle == null){
             return null;
         }
    	 String boardType = getBoardType(bundle.getInt("board_type"));
         String entriesURL = "https://whooing.com/api/bbs/" + boardType + "/" + bundle.getInt("bbs_id") + ".json";
         List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
         
         String subject = bundle.getString("subject");
         String contents = bundle.getString("contents");
         
         nameValuePairs.add(new BasicNameValuePair("contents", contents));
         nameValuePairs.add(new BasicNameValuePair("subject", subject));
         JSONObject result = callApiPut(entriesURL, appID, token, appKey, tokenSecret, appSection, nameValuePairs);
         return result;
    }
    
    public JSONObject putBbsReply(String appSection, String appID, String token, 
            String appKey, String tokenSecret, Bundle bundle) {
    	if(bundle == null){
            return null;
        }
   	 	String boardType = getBoardType(bundle.getInt("board_type"));
		String entriesURL = "https://whooing.com/api/bbs/" + boardType + "/"
				+ bundle.getInt("bbs_id") + "/"
				+ bundle.getString("comment_id") + ".json";
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        
        String contents = bundle.getString("contents");
        
        nameValuePairs.add(new BasicNameValuePair("contents", contents));
        JSONObject result = callApiPut(entriesURL, appID, token, appKey, tokenSecret, appSection, nameValuePairs);
        return result;
	}
    
    public JSONObject delBbsComment(String appSection, String appID, String token, 
            String appKey, String tokenSecret, Bundle bundle) {
        if(bundle == null){
            return null;
        }
        String boardType = getBoardType(bundle.getInt("board_type"));
        String entriesURL = "https://whooing.com/api/bbs/" + boardType + "/" +  bundle.getInt("bbs_id") 
                + "/" + bundle.getString("comment_id") + "/" + bundle.getInt("addition_id") + ".json";
        JSONObject result = callApiDelete(entriesURL, appID, token, appKey, tokenSecret, appSection);
        return result;
    }
    
    
    /**
     * @param   type    board type integer value
     * @return board type string for composition URL
     * */
    public String getBoardType(int type){
        String boardType = "free";
        if(type == BbsListFragment.BOARD_TYPE_FREE){
            boardType = "free";
        }else if(type == BbsListFragment.BOARD_TYPE_MONEY_TALK){
            boardType = "moneytalk";
        }else if(type == BbsListFragment.BOARD_TYPE_COUNSELING){
            boardType = "counseling";
        }else if(type == BbsListFragment.BOARD_TYPE_WHOOING){
            boardType = "whooing";
        }
        return boardType;
    }

	

} public class Board extends AbstractAPI{

	public JSONObject postReply(String appSection, String appID, String token, 
            String appKey, String tokenSecret, Bundle bundle){
        String entriesURL = "https://whooing.com/api/bbs/";
        if(bundle == null){
            return null;
        }
        String category = bundle.getString("category");
        int bbsId = bundle.getInt("bbs_id");
        String contents = bundle.getString("contents");
        entriesURL = entriesURL + category + "/" + bbsId + ".json";
        
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("contents", contents));
        
        JSONObject result = callRawApiPost(entriesURL, appID, token, appKey, tokenSecret, appSection, nameValuePairs);
        return result;
    }

	public JSONObject postComment(String appSection, String appID, String token, 
            String appKey, String tokenSecret, Bundle bundle){
		String entriesURL = "https://whooing.com/api/bbs/";
        if(bundle == null){
            return null;
        }
        String category = bundle.getString("category");
        int bbsId = bundle.getInt("bbs_id");
        String contents = bundle.getString("contents");
        String commentId = bundle.getString("comment_id");
        entriesURL = entriesURL + category + "/" + bbsId + "/" + commentId + ".json";
        
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("contents", contents));
        
        JSONObject result = callRawApiPost(entriesURL, appID, token, appKey, tokenSecret, appSection, nameValuePairs);
        return result;
	} 
} public class Entries extends AbstractAPI{
    
    public JSONObject getLatest(String appSection, String appID, String token, 
            String appKey, String tokenSecret, int limit){
        String entriesURL = "https://whooing.com/api/entries/latest.json_array"
                +"?section_id=" +appSection + "&limit=" + limit;
        JSONObject result = callApi(entriesURL, appID, token, appKey, tokenSecret);
        return result;
    }
    
    public JSONObject insertEntry(String appSection, String appID, String token, 
            String appKey, String tokenSecret, Bundle bundle){
        String entriesURL = "https://whooing.com/api/entries.json_array";
        if(bundle == null){
            return null;
        }
        
        /*String serializedString = getSerializedObject(appSection, bundle);
        if(serializedString == null){
            return null;
        }*/
        
        JSONObject result = callApiPost(entriesURL, appID, token, appKey, tokenSecret, appSection, bundle);
        return result;
    }
    
    public String getSerializedObject(String sectionId, Bundle b){
        if(b == null){
            return null;
        }
        String value = "";
        AccountsEntity left = b.getParcelable("l_account");
        AccountsEntity right = b.getParcelable("r_account");
        Double amount = b.getDouble("money");
        
        value = "?section_id=" + sectionId + "&entry_date=" + b.getInt("entry_date")
                + "&l_account=" + left.accountType + "&l_account_id=" + left.account_id 
                + "&r_account=" + right.accountType + "&r_account_id" + right.account_id
                + "&item=" + b.getString("item") + "&money=" + String.valueOf(amount)
                + "&memo="
                ;
        return value;
    }
} public class GeneralApi extends AbstractAPI {
    /**
     * Call RPC from given API
     * @param   url         Url address to call
     * @param   appID       Application ID
     * @param   token       Token
     * @param   appKey      Application Key
     * @param   tokenSecret Secret key for token
     * @return  Returns JSONObject for result, or null if it fails      
     * */
    public JSONObject getInfo(String url, String appID, 
    		String token, String appKey, String tokenSecret){
        return callApi(url, appID, token, appKey, tokenSecret);
    }
} public class PostIt extends AbstractAPI{

	public JSONObject postPostIt(String appSection, String appID, String token, 
            String appKey, String tokenSecret, Bundle bundle){
        String entriesURL = "https://whooing.com/api/post_it.json";
        if(bundle == null){
            return null;
        }
        String page = bundle.getString("page");
        String contents = bundle.getString("contents");
        
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("page", page));
        nameValuePairs.add(new BasicNameValuePair("contents", contents));
        nameValuePairs.add(new BasicNameValuePair("section_id", appSection));
        
        JSONObject result = callRawApiPost(entriesURL, appID, token, appKey, tokenSecret, appSection, nameValuePairs);
        return result;
    }

    /**
     * @param appSection
     * @param appID
     * @param token
     * @param appKey
     * @param tokenSecret
     * @param bundle
     * @return
     */
    public JSONObject delPostIt(String appSection, String appID, String token, 
            String appKey, String tokenSecret, Bundle bundle) {
        if(bundle == null){
            return null;
        }
        String entriesURL = "https://whooing.com/api/post_it/" + bundle.getInt("post_it_id") + ".json";
        JSONObject result = callApiDelete(entriesURL, appID, token, appKey, tokenSecret, appSection);
        return result;
    }

    /**
     * @param aPP_SECTION
     * @param aPP_ID
     * @param rEAL_TOKEN
     * @param aPP_SECRET
     * @param tOKEN_SECRET
     * @param mBundle
     * @return
     */
    public JSONObject putPostIt(String appSection, String appID, String token, 
            String appKey, String tokenSecret, Bundle bundle) {
    	 if(bundle == null){
             return null;
         }
         String entriesURL = "https://whooing.com/api/post_it/" + bundle.getInt("post_it_id") + ".json";
         List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
         nameValuePairs.add(new BasicNameValuePair("contents", bundle.getString("contents")));
         nameValuePairs.add(new BasicNameValuePair("section_id", appSection));
         JSONObject result = callApiPut(entriesURL, appID, token, appKey, tokenSecret, appSection, nameValuePairs);
         return result;
    }

} public class Section extends AbstractAPI {
	/**
	 * Get all sections
	 * @param	appID		Application ID
	 * @param	token		Token
	 * @param	appKey		Application Key
	 * @param	tokenSecret	Secret key for token
	 * @return	Returns JSONObject for result, or null if it fails		
	 * */
	public JSONObject getSections(String appID, String token, String appKey, String tokenSecret){
		String url = "https://whooing.com/api/sections.json_array";
		return callApi(url, appID, token, appKey, tokenSecret);
	}
} public class UserAPI extends AbstractAPI {
    /**
     * Get User ID
     * @param   appID       Application ID
     * @param   token       Token
     * @param   appKey      Application Key
     * @param   tokenSecret Secret key for token
     * @return  Returns JSONObject for result, or null if it fails      
     * */
    public JSONObject getUserInfo(String appID, String token, String appKey, String tokenSecret){
        String url = "https://whooing.com/api/user.json";
        return callApi(url, appID, token, appKey, tokenSecret);
    }

    /**
    * Get User ID
    * @param   appID       Application ID
    * @param   token       Token
    * @param   appKey      Application Key
    * @param   tokenSecret Secret key for token
    * @return  Returns JSONObject for result, or null if it fails      
    * */
    public JSONObject putUserInfo(String appID, String token, String appKey, 
            String tokenSecret, Bundle bundle) {
        if(bundle == null){
            return null;
        }
        String entriesURL = "https://whooing.com/api/user.json";
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("username", bundle.getString("username")));
        JSONObject result = callApiPut(entriesURL, appID, token, appKey, tokenSecret, Define.APP_SECTION, nameValuePairs);
        return result;
    }
} public class WhooingCalendar {

	static public String getTodayYYYYMMDD(){
		Calendar rightNow = Calendar.getInstance(); 
		
		int year = rightNow.get(Calendar.YEAR);
		int month = rightNow.get(Calendar.MONTH);
		int day = rightNow.get(Calendar.DAY_OF_MONTH);
		month = month + 1;    //달은 0~11이다.
		String monthString = "";
		String dayString = "";
		if(day < 10)
			dayString += "0";
		if(month < 10)
			monthString += "0";
		monthString +=month;
		dayString += day;
		
		return ""+year+monthString+dayString;
	}

    static public int getTodayYYYYMMDDint(){
        String str = getTodayYYYYMMDD();
        
        int date = 0;
        try{
            date = Integer.parseInt(str);
        }catch(NumberFormatException e){
            return 0;
        }
        return date;
    }
    
    static public String getTodayYYYYMM(){
        Calendar rightNow = Calendar.getInstance(); 
        
        int year = rightNow.get(Calendar.YEAR);
        int month = rightNow.get(Calendar.MONTH);
        month = month + 1;
        String monthString = "";
        if(month < 10){
            monthString += "0";
        }
        monthString += month;
        return "" + year + monthString;
    }
    
    static public String getTodayLocale(Context context){
    	Define.gettingLoginInfo(context);
        Locale locale = new Locale(Define.LOCALE_LANGUAGE, Define.COUNTRY_CODE);
        Calendar calendar = Calendar.getInstance(); 
        java.text.DateFormat df = java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM, locale);
        String date = df.format(calendar.getTime()).toString();
        return date;
    }
    
    static public String getPreMonthYYYYMM(int premonth){
        Calendar rightNow = Calendar.getInstance(); 
        rightNow.add(Calendar.MONTH, -(premonth));
        int year = rightNow.get(Calendar.YEAR);
        int month = rightNow.get(Calendar.MONTH);
        month = month + 1;
        String monthString = "";
        if(month < 10)
            monthString += "0";
        monthString += month;
        return "" + year + monthString;
    }
    
    static public String getPreMonthYYYYMMDD(int premonth){
        Calendar rightNow = Calendar.getInstance(); 
        rightNow.add(Calendar.MONTH, -(premonth));
        int year = rightNow.get(Calendar.YEAR);
        int month = rightNow.get(Calendar.MONTH);
        int days = rightNow.get(Calendar.DATE);
        month = month + 1;
        String monthString = "";
        if(month < 10)
            monthString += "0";
        monthString += month;
        
        String dayString = "";
        if(days < 10){
            dayString += "0";
        }
        dayString += days;
        
        return "" + year + monthString + dayString;
    }
    
    static public String getPreMonthLocale(Context context, int premonth){
    	Define.gettingLoginInfo(context);
        Locale locale = new Locale(Define.LOCALE_LANGUAGE, Define.COUNTRY_CODE);
        Calendar calendar = Calendar.getInstance(); 
        calendar.add(Calendar.MONTH, -(premonth));
        java.text.DateFormat df = java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM, locale);
        String date = df.format(calendar.getTime()).toString();
        return date;
    }
    
    static public String getNextMonthYYYYMM(int nextMonth){
        Calendar rightNow = Calendar.getInstance(); 
        rightNow.add(Calendar.MONTH, nextMonth);
        int year = rightNow.get(Calendar.YEAR);
        int month = rightNow.get(Calendar.MONTH);
        month = month + 1;
        String monthString = "";
        if(month < 10)
            monthString += "0";
        monthString += month;
        
        
        return "" + year + monthString;
    }
    
    static public String getLocaleDateInt(int date){
        int year = date / 10000;
        int month = (date % 10000) / 100;
        int day = month % 100;
        return getLocaleDateString(year,month,day,java.text.DateFormat.MEDIUM);        
    }
    
    static public String getLocaleDateString(int year, int month, int day){
        return getLocaleDateString(year,month,day,java.text.DateFormat.MEDIUM);
    }
    
    static public String getLocaleDateString(int year, int month, int day, int style){
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month, day);
        Locale locale = new Locale(Define.LOCALE_LANGUAGE, Define.COUNTRY_CODE);
        java.text.DateFormat df = java.text.DateFormat.getDateInstance(style, locale);
        String date = df.format(calendar.getTime()).toString();
        return date;
    }
    
    static public int getWhooingStyleDateInt(int year, int month, int day){
        return ((year * 10000) + (month * 100) + day);
    }
    
}
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import net.wisedog.android.whooing.Define;
import net.wisedog.android.whooing.WhooingApplication;
import net.wisedog.android.whooing.activity.BbsListFragment;
import net.wisedog.android.whooing.api.AccountsApi;
import net.wisedog.android.whooing.api.BbsApi;
import net.wisedog.android.whooing.api.Board;
import net.wisedog.android.whooing.api.Entries;
import net.wisedog.android.whooing.api.GeneralApi;
import net.wisedog.android.whooing.api.PostIt;
import net.wisedog.android.whooing.api.Section;
import net.wisedog.android.whooing.api.UserAPI;
import net.wisedog.android.whooing.utils.WhooingCalendar;
import org.json.JSONObject;
/*
 * Copyright (C) 2013 Jongha Kim
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.wisedog.android.whooing.network;





/**
 * A thread for Rest API
 * @author Wisedog(me@wisedog.net)
 * */
public class ThreadRestAPI extends Thread {
	private Handler mHandler;
	private int mAPIName;
	private Bundle mBundle;
	
	public ThreadRestAPI(Handler mHandler, int apiName) {
        super();
        checkLoginInfo();
        this.mHandler = mHandler;
        this.mAPIName = apiName;
    }
	
	public ThreadRestAPI(Handler mHandler, int apiName, Bundle bundle) {
        super();
        checkLoginInfo();
        this.mHandler = mHandler;
        this.mAPIName = apiName;
        this.mBundle = bundle;
    }

	private void checkLoginInfo() {	    
        SharedPreferences prefs = WhooingApplication.getInstance().
                getApplicationContext().getSharedPreferences(Define.SHARED_PREFERENCE, 0);    //0 is MODE_PRIVATE
        Define.REAL_TOKEN = prefs.getString(Define.KEY_SHARED_TOKEN, null);
        Define.PIN = prefs.getString(Define.KEY_SHARED_PIN, null);
        Define.TOKEN_SECRET = prefs.getString(Define.KEY_SHARED_TOKEN_SECRET, null);
        Define.APP_SECTION = prefs.getString(Define.KEY_SHARED_SECTION_ID, null);
        Define.USER_ID = prefs.getInt(Define.KEY_SHARED_USER_ID, 0);
        Define.CURRENCY_CODE = prefs.getString(Define.KEY_SHARED_CURRENCY_CODE, null);
        Define.COUNTRY_CODE = prefs.getString(Define.KEY_SHARED_COUNTRY_CODE, null);
        Define.LOCALE_LANGUAGE = prefs.getString(Define.KEY_SHARED_LOCALE_LANGUAGE, "");
        Define.TIMEZONE = prefs.getString(Define.KEY_SHARED_TIMEZONE, null);
		if (Define.DEBUG == true) {
			Log.i("wisedog", "user_id: " + Define.USER_ID + " app_section : "
					+ Define.APP_SECTION + " real_token:" + Define.REAL_TOKEN
					+ " pin : " + Define.PIN + " token_secret : "
					+ Define.TOKEN_SECRET);
			Log.i("wisedog", "country: " + Define.COUNTRY_CODE + " currency: "
					+ Define.CURRENCY_CODE + " Locale : "
					+ Define.LOCALE_LANGUAGE + " Timezone: " + Define.TIMEZONE);
		}
		
	}

	@Override
	public void run() {
		JSONObject result = null;
		String startDate = null;
		String endDate = null;		 
		String requestUrl = null;
		
		int boardType = BbsListFragment.BOARD_TYPE_FREE;
		String type = "";
		if(mAPIName == Define.API_GET_BOARD 
				|| mAPIName == Define.API_GET_BOARD_ARTICLE
				|| mAPIName == Define.API_POST_BOARD_COMMENT 
				|| mAPIName == Define.API_GET_BOARD_COMMENT){
		    if (mBundle == null) {
                Log.e(ThreadRestAPI.class.toString(),
                        "Not enough information for API_GET_BOARD or API_GET_BOARD_ARTICLE");
                sendMessage(null, mAPIName);
                return;
            }
		    boardType = mBundle.getInt("board_type");
	        if(boardType == BbsListFragment.BOARD_TYPE_FREE){
	            type = "free";
	        }else if(boardType == BbsListFragment.BOARD_TYPE_MONEY_TALK){
	            type = "moneytalk";
	        }else if(boardType == BbsListFragment.BOARD_TYPE_COUNSELING){
	            type = "counseling";
	        }else if(boardType == BbsListFragment.BOARD_TYPE_WHOOING){
	            type = "whooing";
	        }
		}
		if(Define.DEBUG){
		    Log.d("wisedog", "API Thread : " + mAPIName);
		}
		        
		switch(mAPIName){
		case Define.API_GET_SECTIONS:
		{
			Section section = new Section();
			result = section.getSections(Define.APP_ID, Define.REAL_TOKEN, 
					Define.APP_SECRET, Define.TOKEN_SECRET);
			break;
		}
        case Define.API_GET_BUDGET:
        {
            GeneralApi budget = new GeneralApi();
            if (mBundle == null) {
                Log.e(ThreadRestAPI.class.toString(), "Not enough information for API_GET_MOUNTAIN");
                sendMessage(null, mAPIName);
                return;
            }
            startDate = mBundle.getString("start_date");
            endDate = mBundle.getString("end_date");
            String account = mBundle.getString("account");
            String requestURL = "https://whooing.com/api/budget/" + account + ".json_array?section_id=" + 
                    Define.APP_SECTION + "&start_date=" + startDate + "&end_date=" + endDate;
            if(Define.DEBUG){
                Log.d("wisedog", "app_id="+Define.APP_ID + ", real_token = " + Define.REAL_TOKEN + ",app_secret = " + Define.APP_SECRET + ", token = "+ Define.TOKEN_SECRET);
            }            
            result = budget.getInfo(requestURL, Define.APP_ID, Define.REAL_TOKEN, Define.APP_SECRET,
                    Define.TOKEN_SECRET);
            break;
        }
        case Define.API_GET_BALANCE:
        {
            String date = "";
            if (mBundle == null) {
                date = WhooingCalendar.getTodayYYYYMMDD();