package com.airson.alive.activity;

import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;

import com.airson.alive.R;
import com.airson.alive.activity.base.BaseActivity;
import com.airson.alive.model.ResponseModel;
import com.airson.alive.model.UserResponseModel;
import com.airson.alive.network.ApiClient;
import com.airson.alive.network.ApiInterface;
import com.airson.alive.preference.Preferences;
import com.airson.alive.utils.CommonUtils;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Calendar;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MedicalIDActivity extends BaseActivity{
    @BindView(R.id.saveBtn)
    Button btnSave;
    @BindView(R.id.relationLayout)
    LinearLayout relationLayout;
    @BindView(R.id.relationSpinner)
    Spinner relationSpinner;
    @BindView(R.id.firstName)
    EditText edtFirstName;
    @BindView(R.id.secondName)
    EditText edtSecondName;
    @BindView(R.id.lastName)
    EditText edtLastName;
    @BindView(R.id.et_email)
    EditText emailEditText;
    @BindView(R.id.et_mobile)
    EditText mobileEditText;
    @BindView(R.id.mobileText)
    TextView mobileText;
    @BindView(R.id.altNo)
    EditText edtAltNo;
    @BindView(R.id.address)
    EditText edtAddress;
    @BindView(R.id.address1)
    EditText edtAddress1;
    @BindView(R.id.pincode)
    EditText edtPinCode;
    @BindView(R.id.dobText)
    TextView txtdob;
    @BindView(R.id.rgGender)
    RadioGroup rgGroup;
    @BindView(R.id.stateSpinner)
    Spinner stateSpinner;
    @BindView(R.id.citySpinner)
    Spinner citySpinner;
    @BindView(R.id.profileImageView)
    ImageView profileImageView;


    String firstname = "", lastname = "", secondname = "", gender = "", dob = "", email = "", relation = "Self", mobile = "";
    String stateString = "", cityString = "";
    private int mYear, mMonth, mDay, mHour, mMinute;

    private static final int SELECT_PHOTO = 11111;
    private static final int CAPTURE_PHOTO = 22222;
    String filepath = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_medicalid);
        setUnBinder(ButterKnife.bind(this));
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("Medical ID");

        relationLayout.setVisibility(View.GONE);
        mobileEditText.setText(Preferences.getInstance().getMobile(this));
        mobileEditText.setEnabled(false);
        txtdob.setText(CommonUtils.getCurrentDate("dd/mm/yyyy"));
        rgGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                RadioButton radioSexButton=(RadioButton)findViewById(radioGroup.getCheckedRadioButtonId());
                gender = radioSexButton.getText().toString();
            }
        });

        ArrayAdapter<String> stateAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, this.getResources().getStringArray(R.array.state_array));
        stateAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        stateSpinner.setAdapter(stateAdapter);

        ArrayAdapter<String> cityAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, this.getResources().getStringArray(R.array.city_array));
        cityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        citySpinner.setAdapter(cityAdapter);

        stateSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                stateString = parent.getItemAtPosition(position).toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        citySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                cityString = parent.getItemAtPosition(position).toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    @Override
    protected void setUp() {

    }

    @OnClick(R.id.dobText)
    public void selectDOB() {
        // Get Current Date
        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);


        DatePickerDialog datePickerDialog = new DatePickerDialog(this,
                new DatePickerDialog.OnDateSetListener() {

                    @Override
                    public void onDateSet(DatePicker view, int year,
                                          int monthOfYear, int dayOfMonth) {

                        txtdob.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);

                    }
                }, mYear, mMonth, mDay);
        datePickerDialog.show();
    }

    @OnClick(R.id.saveBtn)
    public void updateDetails(View view){

        if (CommonUtils.isInternetOn(this, true)) {
            if (isValidInput()) {
                showLoading();
                try {
                    ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
                    Call<ResponseModel> call = apiService.addMedicalID(Preferences.getInstance().getMobile(MedicalIDActivity.this), Preferences.getInstance().getAuthToken(MedicalIDActivity.this),
                                                    firstname, secondname, lastname, gender, dob, email, relation);
                    call.enqueue(new Callback<ResponseModel>() {
                        @Override
                        public void onResponse(Call<ResponseModel> call, Response<ResponseModel> response) {
                            hideLoading();
                            if (response.body() != null) {
                                if (response.body().isError() == false) {
                                    Log.v("response===",  response.body().toString());
                                    Preferences.getInstance().setIsAddMedicalID(MedicalIDActivity.this, true);
//                                    Preferences.getInstance().setAuthToken(MedicalIDActivity.this, response.body().getUser().getAuthtoken());
                                    showMessage(response.body().getMessage());
                                    Intent intent = new Intent(MedicalIDActivity.this, HomeActivity.class);
                                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                                    startActivity(intent);
                                    finish();

                                } else {
                                    showMessage(response.body().getMessage());
                                }
                            }
                        }

                        @Override
                        public void onFailure(Call<ResponseModel> call, Throwable t) {
                            // Log error here since request failed
                            hideLoading();
                            showMessage(t.getMessage());


                        }
                    });


                } catch (Exception e) {
                    e.printStackTrace();

                }
            }
        }

    }

    private boolean isValidInput() {

        Boolean isValid = true;
        firstname = edtFirstName.getText().toString();
        secondname = edtSecondName.getText().toString();
        lastname = edtLastName.getText().toString();
        email = emailEditText.getText().toString();
        dob = txtdob.getText().toString();
        mobile = mobileEditText.getText().toString();

        /*if (relation ==null || relation.isEmpty()) {
            isValid = false;
            onError(getString(R.string.select_relation));

        } else*/ if (firstname ==null || firstname.isEmpty()) {
            isValid = false;
            onError(getString(R.string.enter_first_name));

        } /*else if (secondname ==null || secondname.isEmpty()) {
            isValid = false;
            onError(getString(R.string.enter_second_name));
        }*/ else if (lastname ==null || lastname.isEmpty()) {
            isValid = false;
            onError(getString(R.string.enter_last_name));
        } else if (email ==null || email.isEmpty()) {
            isValid = false;
            onError(getString(R.string.enter_email));
        }else if (!CommonUtils.isEmailValid(email)) {
            isValid = false;
            onError(getString(R.string.enter_valid_email));
        }else if (gender ==null || gender.isEmpty()) {
            isValid = false;
            onError(getString(R.string.gender));
        } else if (dob ==null || dob.isEmpty()) {
            isValid = false;
            onError(getString(R.string.select_dob));
        } else if (mobile == null || mobile.isEmpty()){
            isValid = false;
            onError(getString(R.string.enter_mobile_number));
        } else if (mobile.length()>0 && mobile.length()<10){
            isValid = false;
            onError(getString(R.string.invalid_mobile));
        }


        return isValid;
    }


    @OnClick(R.id.profileImageView)
    public void OnClickChooseFile(View view){
        showPictureDialog();
    }

    private void showPictureDialog(){
        AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
        pictureDialog.setTitle("Select Action");
        String[] pictureDialogItems = {
                "From Camera",
                "From Photos" };
        pictureDialog.setItems(pictureDialogItems,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                                startActivityForResult(intent, CAPTURE_PHOTO);
                                break;
                            case 1:
                                choosePhotoFromPhotos();
                                break;
                        }
                    }
                });
        pictureDialog.show();
    }

    public void choosePhotoFromPhotos(){
        Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
        photoPickerIntent.setType("image/*");
        startActivityForResult(photoPickerIntent, SELECT_PHOTO);

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case SELECT_PHOTO:
                if (resultCode == RESULT_OK && data!=null) {
                    try {
                        final Uri imageUri = data.getData();
                        final InputStream imageStream = getContentResolver().openInputStream(imageUri);
                        final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
                        filepath = CommonUtils.saveImage(this, selectedImage);
                        ImageLoader.getInstance().displayImage("file://"+filepath, profileImageView, CommonUtils.GetDisplayOptionForCircularImage(R.mipmap.upload_pic_place_holder));

                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }

                }
                break;

            case CAPTURE_PHOTO:
                if (resultCode == RESULT_OK && data!=null) {
                    Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
                    filepath = CommonUtils.saveImage(this, thumbnail);
                    ImageLoader.getInstance().displayImage("file://"+filepath, profileImageView, CommonUtils.GetDisplayOptionForCircularImage(R.mipmap.upload_pic_place_holder));
                }
                break;
        }

    }
}

