package com.Tricot.calcutator.CalculatorMenu;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.Tricot.calcutator.MyAPI;
import com.Tricot.calcutator.PostItem;
import com.Tricot.calcutator.R;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


public class Calculator_Login extends AppCompatActivity {
    //권한 추가 할것 추가
    String[] permission_list = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE
    };
    private final String TAG = getClass().getSimpleName();
    private final String BASE_URL = "http://211.238.177.158:8888";
    private MyAPI mMyAPI;
    private EditText usernameEditText;
    private EditText passwordEditText;
    String PhoneNum;
    AlertDialog.Builder alert;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calculator__login);
        usernameEditText = findViewById(R.id.username);
        passwordEditText = findViewById(R.id.password);
        //final Button loginButton = findViewById(R.id.loginBtn);
       // loginButton.setImeOptions(EditorInfo.IME_ACTION_DONE);

        final ProgressBar loadingProgressBar = findViewById(R.id.loading);
        initMyAPI(BASE_URL);
        //loginButton.setImeOptions(EditorInfo.IME_ACTION_DONE);
        checkPermission();
        TelephonyManager telManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            Toast.makeText(getApplicationContext(),"전화 권한을 설정해 주세요", Toast.LENGTH_LONG).show();
            checkPermission();
            return;
        }
        PhoneNum = telManager.getLine1Number();
        if(PhoneNum.startsWith("+82")){
            PhoneNum = PhoneNum.replace("+82","0");
        }


    }

    //테스트용 버튼 페이지 넘어가니 삭제 요망 or 주석처리
    public void popup(View v){
        alert=new AlertDialog.Builder(this);
        alert.setTitle("가입문의");
        alert.setMessage("회원 가입 및 사용 문의는 \n 02-851-3000으로 문의바랍니다.");
        alert.show();

    }


    public void checkPermission(){
        //현재 안드로이드 버전이 6.0미만이면 메서드를 종료한다.
        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
            return;

        for(String permission : permission_list){
            //권한 허용 여부를 확인한다.
            int chk = checkCallingOrSelfPermission(permission);

            if(chk == PackageManager.PERMISSION_DENIED){
                //권한 허용을여부를 확인하는 창을 띄운다
                requestPermissions(permission_list,0);
            }
        }
    }


    //테스트용 버튼 페이지 넘어가니 삭제 요망 or 주석처리
    public void test_ddd(View v){

        Intent intent = new Intent(Calculator_Login.this, MainMenu.class);
        startActivity(intent);

    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode==0)
        {
            for(int i=0; i<grantResults.length; i++)
            {
                //허용됬다면
                if(grantResults[i]==PackageManager.PERMISSION_GRANTED){
                    Toast.makeText(getApplicationContext(),"앱을 한번 종료후 다시 실행시켜 주세요", Toast.LENGTH_SHORT).show();
                }
                else {
                }
            }
        }
    }

    private void initMyAPI(String baseUrl) {

        Log.d(TAG, "initMyAPI : " + baseUrl);
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        mMyAPI = retrofit.create(MyAPI.class);
    }

    public void Login_Click(View v) {

        final String name = usernameEditText.getText().toString();
        final String password = passwordEditText.getText().toString();
        Call<List<PostItem>> getCall = mMyAPI.get_posts();


        try {
            getCall.enqueue(new Callback<List<PostItem>>() {

                @Override
                public void onResponse(Call<List<PostItem>> call, Response<List<PostItem>> response) {
                    if( response.isSuccessful()){
                        List<PostItem> mList = response.body();
                        String result ="";
                        for( PostItem item : mList){
                            if(item.getName().equals(name)==true){
                                if (item.getPassword().equals(password)==true){
                                    if (item.getPhonnumber().equals(PhoneNum)==true){
                                        Intent intent = new Intent(Calculator_Login.this, MainMenu.class);
                                        startActivity(intent);
                                        Toast.makeText(getApplicationContext(),"로그인 되었습니다", Toast.LENGTH_SHORT).show();
                                        break;
                                    }else if(item.getPhonnumber().equals(PhoneNum)==false){
                                        checkPermission();
                                        System.out.println(PhoneNum);
                                        Toast.makeText(getApplicationContext(),"허용되지 않은 핸드폰 번호입니다", Toast.LENGTH_SHORT).show();

                                    }
                                }else if(item.getPassword().equals(password)==false){
                                    Toast.makeText(getApplicationContext(),"아이디 패스워드를 확인해주세요", Toast.LENGTH_SHORT).show();
                                }
                            }
                        }
                        PostItem item = new PostItem();
                    }else {
                        Log.d(TAG,"Status Code : " + response.code());
                    }
                }

                @Override
                public void onFailure(Call<List<PostItem>> call, Throwable t) {
                    Log.d(TAG,"Fail msg : " + t.getMessage());
                    Toast.makeText(getApplicationContext(),"인터넷 연결을 확인해주세요", Toast.LENGTH_SHORT).show();
                }
            });
        }catch (Exception e){
            Toast.makeText(getApplicationContext(),"인터넷 연결을 확인해주세요", Toast.LENGTH_SHORT).show();
        }


    }
}