package com.example.myapplication;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private ListView mListView;

    private static String URL = "http://news.6liu.top/news";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //默认加载的页面
        setContentView(R.layout.activity_main);
        mListView = (ListView) findViewById(R.id.new_main);

        //点击事件
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //获得保存网址的隐藏对象
                TextView content= (TextView) view.findViewById(R.id.new_content);
                //传递的activity
                Intent intent = new Intent(MainActivity.this, NewsActivity.class);
                //保存参数
                intent.putExtra("content_url", content.getText().toString());
                //向下传值
                startActivity(intent);
            }
        });
        //发起URL请求
        new NewsAsyncTask().execute(URL);
    }

    /**
     * 实现网络的异步访问
     */
    class NewsAsyncTask extends AsyncTask<String, Void, List<NewBean>>{

        @Override
        protected List<NewBean> doInBackground(String... strings) {
            return getJsonData(strings[0]);
        }

        @Override
        protected void onPostExecute(List<NewBean> newBeans) {
            super.onPostExecute(newBeans);
            NewsAdapter adapter = new NewsAdapter(MainActivity.this, newBeans, mListView);
            mListView.setAdapter(adapter);
        }
    }

    /**
     * 将获取到的json数据转化为NewBean对象
     * @param url
     * @return
     */
    private List<NewBean> getJsonData(String url) {
        List<NewBean> newsBeanList = new ArrayList<>();
        try {
            String jsonString = readStream(new URL(url).openStream());
            NewBean newBean;
            //解析Json数据
            JSONObject jsonObject;
            try{
                jsonObject = new JSONObject(jsonString);
                JSONArray jsonArray = jsonObject.getJSONArray("data");
                for (int i=0; i<jsonArray.length(); i++){
                    jsonObject = jsonArray.getJSONObject(i);
                    newBean = new NewBean();
                    newBean.setId(jsonObject.getString("id"));
                    newBean.setTitle(jsonObject.getString("title"));
                    newBean.setDesc(jsonObject.getString("desc"));
                    newBean.setTime(jsonObject.getString("time"));
                    newBean.setContentUrl(jsonObject.getString("content_url"));
                    newBean.setPicUrl(jsonObject.getString("pic_url"));
                    newsBeanList.add(newBean);
                }
            }catch (JSONException e){
                e.printStackTrace();
            }
        } catch (IOException e){
            e.printStackTrace();
        }
        return newsBeanList;
    }

    /**
     * 用is解析网页返回的数据
     * @param is
     * @return
     */
    private String readStream(InputStream is){
        InputStreamReader isr;
        String result = "";
        try {
            String line = "";
            isr = new InputStreamReader(is, "utf-8");
            BufferedReader br = new BufferedReader(isr);
            while ((line = br.readLine()) != null){
                result += line;
            }
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        return result;
    }
}
