package hf.lskj.com.carstockcount.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;

import java.io.FileReader;
import java.util.List;

import hf.lskj.com.carstockcount.MyApplication;
import hf.lskj.com.carstockcount.R;
import hf.lskj.com.carstockcount.db.User;
import hf.lskj.com.carstockcount.db.UserDaoUtils;
import hf.lskj.com.carstockcount.utils.FileUtils;
import hf.lskj.com.carstockcount.utils.LogUtils;

public class LoginActivity extends BaseActivity {
    EditText etLoginName;
    EditText etPassword;
    Button btLogin;
    Button btInit;
    final int REQUEST_WRITE = 1;//申请权限的请求码

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        setTitle("登录", false);
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
        initView();
        initListener();

    }

    private void initView() {
        etLoginName = (EditText) findViewById(R.id.et_uid);
        etPassword = (EditText) findViewById(R.id.et_password);
        btLogin = (Button) findViewById(R.id.bt_login);
        btInit = (Button) findViewById(R.id.bt_init);
    }

    private void initListener() {
        etPassword.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_GO || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    btLogin.callOnClick();
                    return true;
                }
                return false;
            }
        });

        btInit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT >= 23) {
                    if (ContextCompat.checkSelfPermission(LoginActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        //第一请求权限被取消显示的判断，一般可以不写
                        if (ActivityCompat.shouldShowRequestPermissionRationale(LoginActivity.this,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                            showAlert();
                        } else {
                            //2、申请权限: 参数二：权限的数组；参数三：请求码
                            ActivityCompat.requestPermissions(LoginActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE);
                        }
                    } else {
                        init();
                    }
                } else {
                    init();
                }
            }
        });


        btLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (etLoginName.getText().length() == 0) {
                    etLoginName.setError("请输入登录名");
                } else if (etPassword.getText().length() == 0) {
                    etPassword.setError("请输入密码");
                } else {
                    UserDaoUtils userDaoUtils = new UserDaoUtils(LoginActivity.this);
                    List<User> users = userDaoUtils.queryByKey(etLoginName.getText().toString());
                    if (users.size() == 0) {
                        if (userDaoUtils.dao.count() == 0) {
                            Toast.makeText(LoginActivity.this, "请先初始化数据", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(LoginActivity.this, "此账号不存在", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        User currentUser = users.get(0);
                        if (!currentUser.getPassword().equals(etPassword.getText().toString())) {
                            Toast.makeText(LoginActivity.this, "密码不正确", Toast.LENGTH_SHORT).show();
                        } else {
                            currentUser.setCurrent(true);
                            userDaoUtils.update(currentUser);
                            MyApplication.currentUser = currentUser;
                            startActivity(new Intent(LoginActivity.this, MainActivity.class));
                            finish();
                        }
                    }
                }
            }
        });
    }

    private void init() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            String fileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + FileUtils.FILE_INIT;
            LogUtils.i(fileName);
            try (FileReader fileReader = new FileReader(fileName)) {
                Gson gson = new Gson();
                List<User> initData = gson.fromJson(fileReader, new TypeToken<List<User>>() {
                }.getType());
                if (initData == null || initData.size() == 0) {
                    Toast.makeText(LoginActivity.this, "初始化失败!", Toast.LENGTH_SHORT).show();
                    return;
                }
                UserDaoUtils userDaoUtils = new UserDaoUtils(LoginActivity.this);
                userDaoUtils.dao.deleteAll();
                for (User user : initData) {
                    userDaoUtils.insert(user);
                }
                Toast.makeText(LoginActivity.this, "初始化成功", Toast.LENGTH_SHORT).show();
            } catch (JsonSyntaxException e) {
                e.printStackTrace();
                Toast.makeText(this, "导入失败,数据格式不正确", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(LoginActivity.this, "初始化失败,请检查是否有初始化文件,以及文件存放路径、文件名是否正确", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(LoginActivity.this, "初始化失败,无法读取SD卡!", Toast.LENGTH_SHORT).show();
        }
    }

    private void showAlert() {
        Dialog alertDialog = new AlertDialog.Builder(this).
                setTitle("权限说明").
                setMessage("我们需要这个权限来初始化APP运行所必要的数据").
                setIcon(R.mipmap.ic_launcher).
                setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //2、申请权限: 参数二：权限的数组；参数三：请求码
                        ActivityCompat.requestPermissions(LoginActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE);
                    }
                }).
                setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                }).
                create();
        alertDialog.show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_WRITE && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            init();
        }

    }
}
