package com.saki.ui;

import com.saki.d.n;
import com.saki.encode.Canvart;
import com.saki.ui.method.NinePasswordTransformationMethod;
import com.saki.sqv9.R;

import com.saki.qq.global.Global;
import com.saki.service.NewConnection;
import com.saki.service.NewService;
import com.saki.tools.BitmapUtil;
import com.saki.ui.i.IDR;
import com.saki.ui.i.IUI;
import com.saki.ui.view.DownloadButton;
import com.saki.ui.view.RoundImageView;
import com.saki.ui.view.UpdateView;
import com.setqq.script.javascript.JavaScript;

import android.Manifest;
import android.animation.Animator;
import android.animation.PropertyValuesHolder;
import android.animation.Animator.AnimatorListener;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

public class NewLoginActivity extends Activity implements OnClickListener, IUI {
    public class JellyInterpolator extends LinearInterpolator {
        private float factor;

        public JellyInterpolator() {
            this.factor = 0.15f;
        }

        @Override
        public float getInterpolation(float input) {
            return (float) (Math.pow(2, -10 * input)
                    * Math.sin((input - factor / 4) * (2 * Math.PI) / factor) + 1);
        }
    }

    public static final int CMD_LOGIN_SUCCESS = 0;
    public static final int CMD_LOGIN_FAILT = 1;
    public static final int CMD_VERIFYCODE = 2;
    public static final int CMD_SET_HEAD = 3;
    public static final int CMD_OTHER = 4;
    private LinearLayout layoutBox;
    private LinearLayout layoutAccount;
    private LinearLayout layoutPassword;
    private LinearLayout layoutHead;
    private Button login;
    private EditText account;
    private EditText password;
    private NewConnection connection;
    private RoundImageView head;
    private UpdateView updata;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == CMD_LOGIN_FAILT) {
                recover();
                String error = msg.obj.toString();
                if (error.replace(" ", "").equals("")) {
                    error = "登录失败:请关闭QQ设备锁";
                }
                Toast.makeText(NewLoginActivity.this, error,
                        Toast.LENGTH_LONG).show();
            } else if (msg.what == CMD_SET_HEAD) {
                head.setImageBitmap((Bitmap) msg.obj);
            } else if (msg.what == CMD_VERIFYCODE) {
                byte[] bin = (byte[]) msg.obj;
                new OtherWindow(NewLoginActivity.this,
                        BitmapFactory.decodeByteArray(bin, 0, bin.length),
                        new IDR() {
                            @Override
                            public void result(String value) {
                                if(value==null || value.equals(""))
                                    recover();
                                else
                                    connection.getService().verifyCode(value);
                            }
                        });
            } else if (msg.what == CMD_LOGIN_SUCCESS) {
                startActivity(new Intent(NewLoginActivity.this,
                        PagerActivity.class));
                NewLoginActivity.this.finish();
            }else{
                Toast.makeText(NewLoginActivity.this, msg.obj.toString(),Toast.LENGTH_LONG).show();
            }
        }

        ;
    };
    private ObjectAnimator anim;
    private long mExitTime;
    private PopHit hit;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                Toast t = Toast.makeText(this, "再按一次，退出程序", Toast.LENGTH_SHORT);
                t.setGravity(Gravity.CENTER, 0, 0);
                t.show();
                mExitTime = System.currentTimeMillis();
            } else {
                stopService(new Intent(this, NewService.class));
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    private void getHead(final String qq) {
        new Thread() {
            @Override
            public void run() {
                Global.qq = Long.parseLong(qq);
                Bitmap b = BitmapUtil.loadFace(qq, false);
                updateUI(CMD_SET_HEAD, b);
            }
        }.start();
    }

    private void headAnim() {
        PropertyValuesHolder animator = PropertyValuesHolder.ofFloat("scaleX",
                0.5f, 1f);
        PropertyValuesHolder animator2 = PropertyValuesHolder.ofFloat("scaleY",
                0.5f, 1f);
        ObjectAnimator animator3 = ObjectAnimator.ofPropertyValuesHolder(
                layoutHead, animator, animator2);
        animator3.setDuration(1000);
        animator3.setInterpolator(new JellyInterpolator());
        animator3.start();
    }
    @Override
    public void onClick(View v) {
        String id = account.getText().toString();
        String psd = password.getText().toString();
        if (id == null || psd == null || id.equals("") || psd.equals("")) {
            Toast.makeText(this, "请输入账号密码", Toast.LENGTH_SHORT).show();
            return;
        }
        saveAccount(id,psd);
        getHead(id);
        connection.getService().login(id, psd,updata.getCode());
        anim = ObjectAnimator.ofFloat(layoutBox, "scaleX", 1.0f,
                0.5f);
        anim.setInterpolator(new AccelerateDecelerateInterpolator());
        anim.setDuration(500);
        anim.addListener(new LoginAnimatorListener());
        anim.start();
    }
    private class LoginAnimatorListener implements AnimatorListener{

        private boolean isCancel = false;
        @Override
        public void onAnimationCancel(Animator animation) {
            isCancel = true;
            layoutAccount.setVisibility(View.VISIBLE);
            layoutPassword.setVisibility(View.VISIBLE);
            login.setEnabled(true);
            login.setText("登录");
            layoutBox.setScaleX(1.0f);
        }

        @Override
        public void onAnimationEnd(Animator animation) {
            if(!isCancel) {
                layoutHead.setVisibility(View.VISIBLE);
                layoutBox.setVisibility(View.INVISIBLE);
                headAnim();
            }
        }

        @Override
        public void onAnimationRepeat(Animator animation) {
        }

        @Override
        public void onAnimationStart(Animator animation) {
            login.setEnabled(false);
            login.setText("登录中...");
            layoutAccount.setVisibility(View.INVISIBLE);
            layoutPassword.setVisibility(View.INVISIBLE);
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_new);
        layoutBox = findViewById(R.id.input_layout);
        layoutAccount = findViewById(R.id.input_layout_name);
        layoutPassword = findViewById(R.id.input_layout_psw);
        layoutHead = findViewById(R.id.layout_progress);
        login = findViewById(R.id.main_btn_login);
        account = findViewById(R.id.input_account);
        password = findViewById(R.id.input_password);
        head = findViewById(R.id.head);
        updata = findViewById(R.id.updateView1);
        login.setOnClickListener(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int REQUEST_CODE_CONTACT = 302;
            String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
            //验证是否许可权限
            for (String str : permissions) {
                if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                }
            }
        }
        checkNetWord();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 302: {
                if(grantResults.length>0&&grantResults[0] == PackageManager.PERMISSION_DENIED){
                    if(connection!=null) {
                        stopService(new Intent(this,NewService.class));
                    }
                    this.finish();
                }
                return;
            }
        }

    }

    private void checkNetWord() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getApplicationContext()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();
        boolean connection = false;
        for (int i = 0; i < networkInfo.length; i++) {
            if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
                connection = true;
                break;
            }
        }
        if (!connection) {
            Toast.makeText(this,"无网络",Toast.LENGTH_SHORT).show();
        } else {
            updata.checkUpdate("http://setqqv8.top:8080/SQv8/update.jsp");
            startService(new Intent(this, NewService.class));
            bindService(new Intent(this, NewService.class),this.connection = new NewConnection(this),Context.BIND_AUTO_CREATE);
        }
        initAccount();
        //startActivity(new Intent(this, PagerActivity.class));
    }
    private String getAccount() {
        return getSharedPreferences("login", Context.MODE_PRIVATE).getString(
                "account", "");
    }

    private String getPassWord() {
        return getSharedPreferences("login", Context.MODE_PRIVATE).getString(
                "passWord", "");
    }
    private void initAccount() {
            account.setText(getAccount());
            password.setText(getPassWord());
            password.setTransformationMethod(new NinePasswordTransformationMethod());
    }
    private void saveAccount(String account, String passWord) {
        SharedPreferences sp = getSharedPreferences("login",
                Context.MODE_PRIVATE);
        SharedPreferences.Editor e = sp.edit();
        e.putString("account", account);
        e.putString("passWord", passWord);
        e.commit();
    }
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        if (hasFocus && hit == null) {
            hit = new PopHit(this, getWindow().getDecorView());
        }
        super.onWindowFocusChanged(hasFocus);
    }

    @Override
    protected void onDestroy() {
        if(connection!=null)
            unbindService(connection);
        super.onDestroy();
    }

    private void recover() {
        layoutHead.setVisibility(View.GONE);
        layoutBox.setVisibility(View.VISIBLE);
        if (anim != null&&anim.isRunning()) {
            anim.cancel();
        }else{
            layoutAccount.setVisibility(View.VISIBLE);
            layoutPassword.setVisibility(View.VISIBLE);
            login.setEnabled(true);
            login.setText("登录");
            layoutBox.setScaleX(1.0f);
        }
    }

    @Override
    public void updateUI(int cmd, Object value) {
        Message msg = Message.obtain();
        msg.what = cmd;
        msg.obj = value;
        handler.sendMessage(msg);
    }
}
