package com.bozaixing.mobeweather.activity;

import android.content.Intent;
import android.os.Build;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bozaixing.mobeweather.R;
import com.bozaixing.mobeweather.activity.base.BaseActivity;
import com.bozaixing.mobeweather.constant.Constant;
import com.bozaixing.mobeweather.constant.HttpConstants;
import com.bozaixing.mobeweather.entity.weather.DailyForecast;
import com.bozaixing.mobeweather.entity.weather.Weather;
import com.bozaixing.mobeweather.http.CommonOkhttpClient;
import com.bozaixing.mobeweather.http.listener.DisposeDataListener;
import com.bozaixing.mobeweather.http.request.CommonRequest;
import com.bozaixing.mobeweather.http.request.RequestParams;
import com.bozaixing.mobeweather.service.AutoUpdateService;
import com.bozaixing.mobeweather.utils.SP;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * Descr:   实时天气实现类
 * Author:  bozaixing.
 * Date:    2017-03-30.
 * Email:   654152983@qq.com.
 */

public class WeatherActivity extends BaseActivity {

    /**
     * UI
     */
    private ImageView mBgPhoto;
    public DrawerLayout mDrawerLayout;
    public SwipeRefreshLayout mSwipeRefreshLayout;
    public ScrollView mWeatherLayout;
    public Button titleBtnHome;
    private TextView titleCity;
    private TextView titleUpdateTime;
    private TextView nowDegreeText;
    private TextView nowInfoText;
    private LinearLayout forecastLayout;
    private TextView aqiText;
    private TextView pmText;
    private TextView comfortText;
    private TextView carWashText;
    private TextView travelText;

    private String mWeatherId;



    @Override
    protected int getLayoutResource() {
        return R.layout.activity_weather;
    }

    @Override
    protected void init() {

        if (Build.VERSION.SDK_INT >=21){

            // 获取window中最顶层的view
            View decorView = getWindow().getDecorView();


        }
    }

    /**
     * 初始化显示控件
     */
    @Override
    protected void initView() {
        // init UI
        mBgPhoto = (ImageView) findViewById(R.id.weather_iv_bg_photo);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.weather_drawerlayout);
        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.weather_swipe_refresh);
        mWeatherLayout = (ScrollView) findViewById(R.id.weather_weather_layout);
        titleBtnHome = (Button) findViewById(R.id.weather_btn_title_home);
        titleCity = (TextView) findViewById(R.id.weather_tv_title_city);
        titleUpdateTime = (TextView) findViewById(R.id.weather_tv_title_update_time);
        nowDegreeText = (TextView) findViewById(R.id.weather_tv_now_degree);
        nowInfoText = (TextView) findViewById(R.id.weather_tv_now_info);
        forecastLayout = (LinearLayout) findViewById(R.id.weather_forecast_layout);
        aqiText = (TextView) findViewById(R.id.weather_tv_aqi);
        pmText = (TextView) findViewById(R.id.weather_tv_pm25);
        comfortText = (TextView) findViewById(R.id.weather_tv_comfort);
        carWashText = (TextView) findViewById(R.id.weather_tv_car_wash);
        travelText = (TextView) findViewById(R.id.weather_tv_travel);

    }

    /**
     * 初始化数据的方法
     */
    @Override
    protected void initData() {
        // 获取轻量级数据库缓存的天气信息
        String data = SP.getString(this, Constant.WEAHER_INFO_NAME);
        // 如果由缓存天气信息则解析天气数据
        if (data != null){
            Weather weather = parseWeatherInfoJsonData(data);
            // 获取缓存城市的ID
            mWeatherId = weather.getBasic().getId();
            // 显示天气
            showWeatherInfo(weather);

            // 加载背景图片
            loadBgPhoto();
        }else {
            // 发送请求从服务器获取天气信息
            Intent intent = getIntent();
            mWeatherId = intent.getStringExtra("weather_id");

            // 没有获取到数据之前则隐藏滚动视图控件
            mWeatherLayout.setVisibility(View.INVISIBLE);


            // 调用方法从服务器获取数据
            getServerWeatherData(mWeatherId);
        }

    }

    @Override
    protected void initListener() {

        // 为标题栏的home按钮注册点击监听响应事件
        titleBtnHome.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 如果用户点击了标题栏的主页按钮则打开侧边栏
                mDrawerLayout.openDrawer(GravityCompat.START);
            }
        });

        // 为下拉刷新控件注册监听事件
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // 如果用户进行了下拉刷新则向服务器请求数据
                getServerWeatherData(mWeatherId);
            }
        });

    }


    /**
     * 设置显示天气信息的方法
     * @param weather
     */
    private void showWeatherInfo(Weather weather){

        titleCity.setText(weather.getBasic().getCity());
        titleUpdateTime.setText(weather.getBasic().getUpdate().getLoc().split("")[1]);

        nowDegreeText.setText(weather.getNow().getCond().getCode() + "℃");
        nowInfoText.setText(weather.getNow().getCond().getTxt());

        // 先移除未来天气预报控件里面的子视图
        forecastLayout.removeAllViews();
        // 再添加新的子视图
        for (DailyForecast dailyForecast : weather.getDaily_forecast()){
            View view = LayoutInflater.from(this).inflate(R.layout.layout_forecast_item, forecastLayout, false);
            TextView dataText = (TextView) view.findViewById(R.id.forecast_data_text);
            TextView infoText = (TextView) view.findViewById(R.id.forecast_info_text);
            TextView maxText = (TextView) view.findViewById(R.id.forecast_max_text);
            TextView minText = (TextView) view.findViewById(R.id.forecast_min_text);
            dataText.setText(dailyForecast.getDate());
            infoText.setText(dailyForecast.getCond().getTxt_d());
            maxText.setText(dailyForecast.getTmp().getMax());
            minText.setText(dailyForecast.getTmp().getMin());
            // 添加子视图
            forecastLayout.addView(view);
        }

        aqiText.setText(weather.getAqi().getCity().getAqi());
        pmText.setText(weather.getAqi().getCity().getPm25());

        comfortText.setText("舒适度：" + weather.getSuggestion().getComf().getTxt());
        carWashText.setText("洗车指数：" + weather.getSuggestion().getCw().getTxt());
        travelText.setText("出行建议：" + weather.getSuggestion().getTrav().getTxt());

        // 取得数据后则设置显示滚动视图显示控件
        mWeatherLayout.setVisibility(View.VISIBLE);

        // 启动后台服务
        Intent intent = new Intent(this, AutoUpdateService.class);
        startService(intent);
    }

    /**
     * 从服务器获取天气的json数据
     * @param weatherId 根据城市ID
     */
    public void getServerWeatherData(String weatherId){

        Map<String, String> params = new HashMap<>();
        params.put("city", weatherId);
        params.put("key", Constant.HEFENG_WEATHER_KEY);

        CommonOkhttpClient.sendRequest(CommonRequest.createGetRequest(HttpConstants.HEFENG_WEATHER_URL, new RequestParams(params)),
                new DisposeDataListener() {
                    @Override
                    public void onSuccess(Object responseObj) {
                        String data = responseObj.toString();

                        // 调用方法解析数据
                        Weather weather = parseWeatherInfoJsonData(data);

                        if (weather != null && weather.getStatus().equals("ok")){
                            // 将返回的数据保存到本地的轻量级数据库
                            SP.putString(getApplicationContext(), Constant.WEAHER_INFO_NAME, data);

                            mWeatherId = weather.getBasic().getId();

                            // 更新UI
                            showWeatherInfo(weather);

                        } else {
                            // 提示失败
                            Toast.makeText(getApplicationContext(), "获取天气信息失败", Toast.LENGTH_SHORT).show();
                        }

                        mSwipeRefreshLayout.setRefreshing(false);
                    }

                    @Override
                    public void onFailure(Object reasonObj) {
                        // 提示失败
                        Toast.makeText(getApplicationContext(), "获取天气信息失败", Toast.LENGTH_SHORT).show();

                        mSwipeRefreshLayout.setRefreshing(false);
                    }
                });

        // 加载背景图片
        loadBgPhoto();
    }


    /**
     * 实现解析json是数据的方法
     *
     * @param data
     */
    private Weather parseWeatherInfoJsonData(String data){

        // 验证数据的有效性,如果需要解析的数据不为空
        if (!TextUtils.isEmpty(data)){
            try {
                // 开始解析
                JSONObject jsonObject = new JSONObject(data);

                JSONArray jsonArray = jsonObject.getJSONArray("HeWeather5");
                String weatherContent = jsonArray.getJSONObject(0).toString();

                return new Gson().fromJson(weatherContent, Weather.class);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    /**
     * 实现发送请求加载背景图片的方法
     */
    private void loadBgPhoto(){

        CommonOkhttpClient.sendRequest(CommonRequest.createGetRequest(HttpConstants.GANK_MEIZI_URL, null),
                new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {

                String data = responseObj.toString();
                if (!TextUtils.isEmpty(data)){

                    try {
                        // 解析json数据
                        JSONObject jsonObject = new JSONObject(data);
                        JSONObject result = jsonObject.getJSONObject("result");
                        String photoUrl = result.getString("url");

                        // 为显示控件设置该图片
                        Glide.with(WeatherActivity.this).load(photoUrl).into(mBgPhoto);

                    } catch (JSONException e) {
                        e.printStackTrace();
                        // 加载本地图片
                        Glide.with(WeatherActivity.this).load(R.drawable.weather_bg).into(mBgPhoto);
                    }
                }else {

                    // 加载本地图片
                    Glide.with(WeatherActivity.this).load(R.drawable.weather_bg).into(mBgPhoto);
                }

            }

            @Override
            public void onFailure(Object reasonObj) {
                // 加载本地图片
                Glide.with(WeatherActivity.this).load(R.drawable.weather_bg).into(mBgPhoto);
            }
        });
    }

}
