package com.smf.location;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Toast;


import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class CityActivity extends Activity {
    public AMapLocationClient mLocationClient = null;
    public AMapLocationListener mLocationListener;
    public AMapLocationClientOption mLocationOption = null;
    RecyclerView recyclerview;
    EditText et_search;
    CityAdapter adapter;
    List<City> list = new ArrayList<>();
    List<City> alllist = new ArrayList<>();
    LinearLayoutManager manager;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_city);
        initView();
        initData();
    }
    public void initView(){
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        recyclerview = findViewById(R.id.recyclerview);
        et_search = findViewById(R.id.et_search);
        adapter = new CityAdapter(this,list);
        manager = new LinearLayoutManager(this);
        recyclerview.setLayoutManager(manager);
        recyclerview.setAdapter(adapter);
        et_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                searchCity(charSequence.toString());
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        adapter.setOnItemClickLitener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if(i == -1){
                    Intent intent = new Intent();
                    intent.putExtra("city",adapter.gps);
                    setResult(Activity.RESULT_OK,intent);
                    finish();
                }else{
                    Intent intent = new Intent();
                    intent.putExtra("city",list.get(i).getCity());
                    intent.putExtra("zip",list.get(i).getZip());
                    setResult(Activity.RESULT_OK,intent);
                    finish();
                }

            }
        });
        mLocationListener = new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                adapter.setGps(aMapLocation.getCity());
            }
        };
        mLocationClient = new AMapLocationClient(getApplicationContext());
        mLocationClient.setLocationListener(mLocationListener);
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//        mLocationOption.setOnceLocation(true);
//        mLocationOption.setOnceLocationLatest(true);
        mLocationOption.setNeedAddress(true);
//        mLocationOption.setLocationCacheEnable(false);
        mLocationClient.setLocationOption(mLocationOption);
        mLocationClient.startLocation();
        AMapLocation location = mLocationClient.getLastKnownLocation();
        if(location!=null){
            adapter.setGps(location.getCity());
        }
    }
    public void initData(){
        try {
            JSONArray jsonArray = new JSONArray(readAssetsTxt(this,"prov-city"));
            for(int i=0;i<jsonArray.length();i++){
                City city = new City(jsonArray.getJSONObject(i).getString("pinyin").substring(0,1).toUpperCase(),jsonArray.getJSONObject(i).getString("name"),jsonArray.getJSONObject(i).getString("zip"));
                list.add(city);
            }
            Collections.sort(list, new sortByDate());
            alllist.addAll(list);
            adapter.notifyDataSetChanged();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    public void goback(View v){
        finish();
    }
    public void onClickLetter(View v){
        String letter = "";
        int index = 0;
        if (v.getId() == R.id.btn_a) {
            letter = "A";
        }else if(v.getId() == R.id.btn_b){
            letter = "B";
        }else if(v.getId() == R.id.btn_c){
            letter = "C";
        }else if(v.getId() == R.id.btn_d){
            letter = "D";
        }else if(v.getId() == R.id.btn_e){
            letter = "E";
        }else if(v.getId() == R.id.btn_f){
            letter = "F";
        }else if(v.getId() == R.id.btn_g){
            letter = "G";
        }else if(v.getId() == R.id.btn_h){
            letter = "H";
        }else if(v.getId() == R.id.btn_j){
            letter = "J";
        }else if(v.getId() == R.id.btn_k){
            letter = "K";
        }else if(v.getId() == R.id.btn_l){
            letter = "L";
        }else if(v.getId() == R.id.btn_m){
            letter = "M";
        }else if(v.getId() == R.id.btn_n){
            letter = "N";
        }else if(v.getId() == R.id.btn_p){
            letter = "P";
        }else if(v.getId() == R.id.btn_q){
            letter = "Q";
        }else if(v.getId() == R.id.btn_r){
            letter = "R";
        }else if(v.getId() == R.id.btn_s){
            letter = "S";
        }else if(v.getId() == R.id.btn_t){
            letter = "T";
        }else if(v.getId() == R.id.btn_w){
            letter = "W";
        }else if(v.getId() == R.id.btn_x){
            letter = "X";
        }else if(v.getId() == R.id.btn_y){
            letter = "Y";
        }else if(v.getId() == R.id.btn_z){
            letter = "Z";
        }
        int pos = 0;
        for(int i=0;i<list.size();i++){
            if(list.get(i).getLetter().equals(letter)){
                pos = i;
                break;
            }
        }
//        Log.e("sf",""+pos);
        MoveToPosition(manager,recyclerview,pos);
    }
    public String readAssetsTxt(Context context, String fileName){
        try {
            //Return an AssetManager instance for your application's package
            InputStream is = context.getAssets().open(fileName+".json");
            int size = is.available();
            // Read the entire asset into a local byte buffer.
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            // Convert the buffer into a string.
            String text = new String(buffer, "utf-8");
            // Finally stick the string into the text view.
            return text;
        } catch (IOException e) {
            // Should never happen!
//            throw new RuntimeException(e);
            e.printStackTrace();
        }
        return "读取错误，请检查文件名";
    }
    public void searchCity(String city){
        if(city.equals("")){
            list.clear();
            list.addAll(alllist);
            adapter.notifyDataSetChanged();
        }else{
            list.clear();
            for(int i=0;i<alllist.size();i++){
                if(alllist.get(i).getCity().indexOf(city)!=-1){
                    list.add(alllist.get(i));
                }
            }
            adapter.notifyDataSetChanged();
        }
    }
    static class sortByDate implements Comparator {

        @Override
        public int compare(Object o, Object t1) {
            City city1 = (City)o;
            City city2 = (City)t1;
//            if((byte)city1.getLetter().charAt(0) > (byte)city2.getLetter().charAt(0)){
//                return 1;
//            }
//
//            return -1;
            return city1.getLetter().compareTo(city2.getLetter());
        }
    }
    public static void MoveToPosition(LinearLayoutManager manager, RecyclerView mRecyclerView, int n) {
        mRecyclerView.scrollToPosition(n+1);
        manager.scrollToPositionWithOffset(n+1, 0);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocationClient.onDestroy();
    }
}
