package com.practice.miradil.uyghurweather.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.practice.miradil.uyghurweather.R;
import com.practice.miradil.uyghurweather.util.HttpUtil;
import com.practice.miradil.uyghurweather.util.StatusBarUtils;
import com.practice.miradil.uyghurweather.util.Utility;

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {
    public String nowLocation;
    private Toolbar toolbar;
    private SwipeRefreshLayout swipeRefreshLayout;
    private String codeToWeather[] = new String[] {"晴", "多云", "雨", "雪", "未知"};
    private int codeToImg[] = new int[] {
            R.drawable.sunny,
            R.drawable.cloudy,
            R.drawable.rain,
            R.drawable.snow,
    };
    private int codeToColor[] = new int[] {R.color.sunny, R.color.cloudy, R.color.rain, R.color.snow, R.color.colorPrimary};
    private int dayToId[] = new int[] {R.id.today_temp, R.id.tomor_temp, R.id.after_temp};
    private int dayToIdImg[] = new int[] {R.id.today_temp_img, R.id.tomor_temp_img, R.id.after_temp_img};

    private String getLocation() {
        SharedPreferences preferences = getSharedPreferences("data", MODE_PRIVATE);
        return preferences.getString("now_location", "wlmq");
    }
    private void UpdateThisDay(SharedPreferences preferences, int day) {
        TextView textView = (TextView)findViewById(dayToId[day]);
        ImageView imageView = (ImageView)findViewById(dayToIdImg[day]);
        String low = preferences.getString("low_"+day, "ERROR");
        String high = preferences.getString("high_"+day, "ERROR");
        textView.setText(low+"°C/"+high+"°C");
        int weatherCode = Integer.parseInt(preferences.getString("weather_"+day, "99"));
        weatherCode = Utility.GetWeatherWithCode(weatherCode);
        imageView.setImageResource(codeToImg[weatherCode]);
    }
    private void UpdateBackGround(int weatherCode) {
        toolbar.setBackgroundResource(codeToColor[weatherCode]);
        RelativeLayout layout = (RelativeLayout)findViewById(R.id.content_main);
        layout.setBackgroundResource(codeToColor[weatherCode]);
        StatusBarUtils.setWindowStatusBarColor(this, codeToColor[weatherCode]);
    }
    public void updateUI() {
        SharedPreferences preferences = getSharedPreferences("data", MODE_PRIVATE);
        TextView nowTemp = (TextView)findViewById(R.id.now_temp);
        String temp = preferences.getString("now_temp", "ERROR")+"°C";
        nowTemp.setText(temp);
        int weatherCode = Integer.parseInt(preferences.getString("now_weather", "99"));
        weatherCode = Utility.GetWeatherWithCode(weatherCode);
        UpdateBackGround(weatherCode);
        TextView nowWeather = (TextView)findViewById(R.id.now_temp_txt);
        nowWeather.setText(codeToWeather[weatherCode]);
        ImageView imageView = (ImageView)findViewById(R.id.now_temp_img);
        imageView.setImageResource(codeToImg[weatherCode]);
        for (int i = 0; i < 3; i++)
            UpdateThisDay(preferences, i);
        Snackbar snackbar = Snackbar.make(findViewById(R.id.content_main), "更新成功", Snackbar.LENGTH_SHORT);
        snackbar.getView().setBackgroundResource(codeToColor[weatherCode]);
        snackbar.show();
        swipeRefreshLayout.setRefreshing(false);
    }
    private void updateWeather(Context context, String nowLocation) {
        String address = "https://api.thinkpage.cn/v3/weather/now.json?key=w7gphvih3nfipwky&location="+nowLocation+"&language=zh-Hans&unit=c";
        getNowWeather(address, context);
    }
    private void getNowWeather(String address, final Context context) {
        HttpUtil.sendHttpRequest(address, new HttpUtil.HttpCallBackListener() {
            @Override
            public void onFinish(final String response) {
                Utility.HandleWeatherNowResponse(context, response);
                String address = "https://api.thinkpage.cn/v3/weather/daily.json?key=w7gphvih3nfipwky&location="+nowLocation+"&language=zh-Hans&unit=c&start=0&days=5";
                getWeatherRange(address, context);
            }
            @Override
            public void onError(Exception e) {
                e.printStackTrace();
            }
        });
    }
    private void getWeatherRange(String address, final Context context) {
        HttpUtil.sendHttpRequest(address, new HttpUtil.HttpCallBackListener() {
            @Override
            public void onFinish(final String response) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Utility.HandleWeatherRangeResponse(context, response);
                        updateUI();
                    }
                });
            }
            @Override
            public void onError(Exception e) {
                e.printStackTrace();
            }
        });
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        nowLocation = getLocation();
        setContentView(R.layout.activity_main);
        doToolbarStuff();
        doFloatButtonStuff();
        doSwipeRefreshStuff();
        this.setTitle("    "+(getSharedPreferences("data", MODE_PRIVATE).getString("now_chname", "乌鲁木齐")));
        refresh();
    }
    private void doSwipeRefreshStuff() {
        swipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.swipe_refresh);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });
    }
    private void refresh() {
        this.setTitle("    "+(getSharedPreferences("data", MODE_PRIVATE).getString("now_chname", "乌鲁木齐")));
        nowLocation = getLocation();
        swipeRefreshLayout.setRefreshing(true);
        updateWeather(this, nowLocation);
    }

    private void doFloatButtonStuff() {
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {refresh();}
        });
    }
    private void doToolbarStuff() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.nav_location) {
            Intent intent = new Intent(MainActivity.this, ChooseAreaActivity.class);
            startActivity(intent);
            refresh();
        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
        refresh();
    }
}