package com.renitha.Activity;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.github.gcacace.signaturepad.views.SignaturePad;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.renitha.Interface.APIService;
import com.renitha.Model.APIUrl;
import com.renitha.Model.SetterLogin;
import com.renitha.Pref.Pref;
import com.renitha.R;

import java.io.ByteArrayOutputStream;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class CustomerSignActivity extends AppCompatActivity
{
    private Button btnSave,clear_button;
    private String cust_signature="",str="";

    private SignaturePad signature_view;
    private RadioButton radioBest,radioBetter,radioGood,radioPoor;
    private String rate_us="Best";
    private EditText editTextRemark;
    private Bundle bundle;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_customer_sign);
        radioBest                =       (RadioButton)findViewById(R.id.radioBest);
        radioBetter              =       (RadioButton)findViewById(R.id.radioBetter);
        radioGood                =       (RadioButton)findViewById(R.id.radioGood);
        radioPoor                =       (RadioButton)findViewById(R.id.radioPoor);
        editTextRemark           =       (EditText)findViewById(R.id.editTextRemark);
        signature_view           =       (SignaturePad)findViewById(R.id.signature_view);
        btnSave                  =       (Button) findViewById(R.id.btnSave);
        clear_button             =       (Button) findViewById(R.id.clear_button);

        radioBest.setOnCheckedChangeListener(new Radio_RateUs());
        radioBetter.setOnCheckedChangeListener(new Radio_RateUs());
        radioGood.setOnCheckedChangeListener(new Radio_RateUs());
        radioPoor.setOnCheckedChangeListener(new Radio_RateUs());

        clear_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                signature_view.clearView();
            }
        });

        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveImage();
                showAlert("Are you sure save this record?");
               // fileUpload();
               /* String customer_remark    =   editTextRemark.getText().toString().trim();
                Intent i = new Intent(getApplicationContext(), CameraActivity.class);

                i.putExtra("id",id);
                i.putExtra("flag",flag);
                i.putExtra("CallNo",CallNo);
                i.putExtra("FaultDetails",FaultDetails);
                i.putExtra("ServicePerformed",ServicePerformed);
                i.putExtra("Preventive",Preventive);
                i.putExtra("BreakDown",BreakDown);
                i.putExtra("JobDate",JobDate);
                i.putExtra("StartTime",StartTime);
                i.putExtra("EndTime",EndTime);
                i.putExtra("lat",lat);
                i.putExtra("longi",longi);
                i.putExtra("cust_signature",cust_signature);
                i.putExtra("rate_our_service",rate_us);
                i.putExtra("customer_remark",customer_remark);
                startActivity(i);*/
            }
        });
    }

    class Radio_RateUs implements  CompoundButton.OnCheckedChangeListener
    {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
        {
            if (radioBest.isChecked())
            {
                rate_us = "Best";
            }
            else if (radioBetter.isChecked())
            {
                rate_us = "Better";
            }
            else if (radioGood.isChecked())
            {
                rate_us = "Good";
            }
            else if (radioPoor.isChecked())
            {
                rate_us = "Poor";
            }
        }
    }
    public void saveImage()
    {
        Bitmap myBitmap = signature_view.getSignatureBitmap();
        Bitmap newBitmap = Bitmap.createBitmap(myBitmap.getWidth(), myBitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newBitmap);
        canvas.drawColor(Color.WHITE);
        canvas.drawBitmap(myBitmap, 0, 0, null);
        cust_signature= encodeImage(newBitmap);
    }

    private String encodeImage(Bitmap bm)
    {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG,50,baos);
        byte[] b = baos.toByteArray();
        String encImage = Base64.encodeToString(b, Base64.DEFAULT);
        return encImage;
    }

    private void fileUpload()
    {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Saving...");
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setCancelable(false);
        progressDialog.show();
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(20, TimeUnit.MINUTES)
                .writeTimeout(20, TimeUnit.MINUTES)
                .readTimeout(20, TimeUnit.MINUTES).build();
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        // set your desired log level
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        // add your other interceptors …
        // add logging as last interceptor
        httpClient.addInterceptor(logging);  // <-- this is the important line
        //.client(httpClient.build())
        //.client(client)
       // GsonBuilder gsonBuilder = new GsonBuilder();
       // gsonBuilder.setLenient();
        //Gson gson = gsonBuilder.create();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(APIUrl.BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create(new  Gson()))
                .build();

        String ticket_id            =   Pref.getInstance(getApplicationContext()).getTICKET_ID();
        String customer_remark      =   editTextRemark.getText().toString().trim();
        APIService service          =   retrofit.create(APIService.class);
        Call<SetterLogin> call      =   service.setComplaintPhotoUpload(ticket_id,cust_signature,rate_us,customer_remark);
        call.enqueue(new Callback<SetterLogin>()
        {
            @Override
            public void onResponse(Call<SetterLogin> call, Response<SetterLogin> response)
            {
                Log.d("error",response.body()+"");
                progressDialog.dismiss();
                finish();
                Pref.getInstance(getApplicationContext()).setTICKET_ID("");
                Intent i = new Intent(CustomerSignActivity.this, ViewUserComplaints.class);
                // Specify any activity here e.g. home or splash or login etc
                i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(i);
                if (response.body().getError().equals(true))
                {
                }
                else
                {
                    Toast.makeText(getApplicationContext(), "Information saved Failed", Toast.LENGTH_LONG).show();
                }
            }
            @Override
            public void onFailure(Call<SetterLogin> call, Throwable t)
            {
                progressDialog.dismiss();
                Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
    }
    public void showAlert(String message)
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(Html.fromHtml("<font color='#8472BB'>"+message+"!</font>")).setCancelable(false)
                .setPositiveButton("Submit", new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog, int id)
                    {
                        fileUpload();
                    }
                });
        builder.setNegativeButton("Cancel", null);
        AlertDialog alert = builder.create();
        alert.show();
        Button pbutton = alert.getButton(DialogInterface.BUTTON_POSITIVE);
        pbutton.setTextColor(Color.BLACK);

    }
}
