package com.renitha.Activity;

import android.Manifest;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.renitha.Adapter.RecyclerUserComplaintAssignedAdapter;
import com.renitha.Adapter.RecyclerViewComplaintAdapter;
import com.renitha.Interface.APIService;
import com.renitha.Model.APIUrl;
import com.renitha.Model.InProgress_Response;
import com.renitha.Model.SetterComplaintDetails;
import com.renitha.Model.SetterProfile;
import com.renitha.Model.SetterViewComplaintDetails;
import com.renitha.Pref.Pref;
import com.renitha.R;

import java.util.ArrayList;
import java.util.List;

import me.ibrahimsn.lib.OnItemSelectedListener;
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 ViewComplaintInfoActivity extends AppCompatActivity
{
    private TextView hospitalName,custName,custConatctNo,custEmail,custAddress,userName,userConatctNo,userEmail,userAssignDate,userCompletedDate;
    private TextView ticket_no,ticket_date,complaint_type,serialno,category_name,product_id,make,model,ticket_priority,equp_cond,remark;
    private Button btnDownload;
    private String id;
    private ImageView toolbar_contact;
    private String str;
    private LinearLayout linearLayout;
    RecyclerView recyclerView;
    RecyclerView.LayoutManager recyclerViewlayoutManager;
    ArrayList<SetterViewComplaintDetails> listing;
    RecyclerViewComplaintAdapter recyclerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_complaint_info);
        toolbar_contact = (ImageView) findViewById(R.id.toolbar_contact);
        hospitalName = (TextView) findViewById(R.id.hospitalName);
        custName = (TextView) findViewById(R.id.custName);
        custConatctNo = (TextView) findViewById(R.id.custConatctNo);
        custEmail = (TextView) findViewById(R.id.custEmail);
        custAddress = (TextView) findViewById(R.id.custAddress);
        //userName = (TextView) findViewById(R.id.userName);
        //userConatctNo = (TextView) findViewById(R.id.userConatctNo);
       // userEmail = (TextView) findViewById(R.id.userEmail);

        ticket_no = (TextView) findViewById(R.id.ticket_no);
        ticket_date = (TextView) findViewById(R.id.ticket_date);
        complaint_type = (TextView) findViewById(R.id.complaint_type);
        serialno = (TextView) findViewById(R.id.serialno);
        category_name = (TextView) findViewById(R.id.category_name);
        product_id = (TextView) findViewById(R.id.product_id);
        make = (TextView) findViewById(R.id.make);
        model = (TextView) findViewById(R.id.model);
        ticket_priority = (TextView) findViewById(R.id.ticket_priority);
        equp_cond = (TextView) findViewById(R.id.equp_cond);
        remark = (TextView) findViewById(R.id.remark);
        btnDownload = (Button) findViewById(R.id.btnDownload);
        linearLayout = (LinearLayout) findViewById(R.id.linearLayout);
        Bundle bundle               =       getIntent().getExtras();
        id                          =       bundle.getString("id");

        recyclerView        =   (RecyclerView)findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(true);
        recyclerViewlayoutManager   =   new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(recyclerViewlayoutManager);
        listing = new ArrayList<>();

      /*  userConatctNo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + userConatctNo.getText().toString()));
                if (ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(ViewComplaintInfoActivity.this,
                            new String[]{Manifest.permission.CALL_PHONE}, 143);
                } else {
                    startActivity(intent);
                }
            }
        });

        userEmail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(Intent.ACTION_SEND);
                i.setType("message/rfc822");
                String email_id =  userEmail.getText().toString();
                i.putExtra(Intent.EXTRA_EMAIL  , new String[]{email_id});
                i.putExtra(Intent.EXTRA_SUBJECT, "");
                i.putExtra(Intent.EXTRA_TEXT   , "");
                try {
                    startActivity(Intent.createChooser(i, "Send mail..."));
                } catch (android.content.ActivityNotFoundException ex) {
                    Toast.makeText(ViewComplaintInfoActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
                }
            }
        });*/
        toolbar_contact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent   =   new Intent(ViewComplaintInfoActivity.this, ContactUsActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.enter, R.anim.exit);
            }
        });

        btnDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DownloadManager downloadmanager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
                Uri uri = Uri.parse(str);

                DownloadManager.Request request = new DownloadManager.Request(uri);
                request.setTitle("Renitha Report");
                request.setDescription("Downloading");
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,"renitha_"+System.currentTimeMillis() + ".pdf");
                downloadmanager.enqueue(request);
            }
        });
        JSON_GET_INFO();
        JSON_GET_COMPLAINT_HISTORY();
    }
    private void JSON_GET_INFO()
    {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Wait...");
        progressDialog.show();
        progressDialog.setCancelable(false);
        progressDialog.setCanceledOnTouchOutside(false);
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(APIUrl.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        APIService service = retrofit.create(APIService.class);

        Call<SetterComplaintDetails> call = service.getComplaintInfo(id);
        call.enqueue(new Callback<SetterComplaintDetails>()
        {
            @Override
            public void onResponse(Call<SetterComplaintDetails> call, Response<SetterComplaintDetails> response)
            {
                progressDialog.dismiss();
                if (response.body().getError().equals(true))
                {
                    JSON_GET_COMPLAINT_HISTORY();
                    str = response.body().getService_pdf_url();
                    hospitalName.setText(response.body().getHospital_name());
                    custName.setText(response.body().getCust_name());
                    custConatctNo.setText(response.body().getCust_contact());
                    custEmail.setText(response.body().getCust_email());
                    custAddress.setText(response.body().getHospital_address());

                   // userName.setText(response.body().getUser_name());
                    if(!response.body().getUser_contact().equals(""))
                    {
                      //  userConatctNo.setText(Html.fromHtml("<u>"+response.body().getUser_contact()+"</u>"));
                    }
                     if(!response.body().getUser_email().equals(""))
                     {
                        // userEmail.setText(Html.fromHtml("<u>"+response.body().getUser_email()+"</u>"));
                     }
                    if(!str.equals(""))
                    {
                        btnDownload.setVisibility(View.VISIBLE);
                    }
                    else
                    {
                        btnDownload.setVisibility(View.GONE);
                    }
                 //   userAssignDate.setText(response.body().getAssign_date());
                 //   userCompletedDate.setText(response.body().getCompleted_date());

                    ticket_no.setText("Complaint No : " +response.body().getTicket_no());
                    ticket_date.setText("Complaint Date : " +response.body().getTicket_date());
                    complaint_type.setText("Complaint Type : " +response.body().getComplaint_type());
                    serialno.setText("Serial No : " +response.body().getSerialno());
                    category_name.setText("Category name : " +response.body().getCategory_name());
                    product_id.setText("Product name : " +response.body().getProduct_id());
                    make.setText("Make : " +response.body().getMake());
                    model.setText("Model : " +response.body().getModel());
                    ticket_priority.setText("Priority : " +response.body().getTicket_priority());
                    equp_cond.setText("Equipment Condition : " +response.body().getEqup_cond());
                    remark.setText("Remark : " +response.body().getRemark());

                    //response.body().getPhotoList();
                    for(int i=0;i<response.body().getPhotoList().size();i++)
                    {
                        final String str = response.body().getPhotoList().get(i).getPhoto_url();
                        TextView valueTV = new TextView(getApplicationContext());
                        valueTV.setText(Html.fromHtml("<u>Download</u>"));
                        valueTV.setPadding(10,5,0,5);
                        valueTV.setTextColor(Color.BLACK);
                        valueTV.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
                        valueTV.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                DownloadManager downloadmanager = (DownloadManager) getApplicationContext().getSystemService(Context.DOWNLOAD_SERVICE);
                                Uri uri = Uri.parse(str);

                                DownloadManager.Request request = new DownloadManager.Request(uri);
                                request.setTitle("Renitha Downloaded Image");
                                request.setDescription("Downloading");
                                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,"renitha_"+System.currentTimeMillis() + ".png");
                                downloadmanager.enqueue(request);
                            }
                        });
                        linearLayout.addView(valueTV);
                    }
                    /*Glide.with(getContext())
                            .load(response.body().getPhoto_img())
                            .apply(new RequestOptions().centerCrop()
                                    .circleCrop())
                            .into(imgViewPic);
                    */
                }
            }
            @Override
            public void onFailure(Call<SetterComplaintDetails> call, Throwable t)
            {
                progressDialog.dismiss();
                Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
    }
    public void JSON_GET_COMPLAINT_HISTORY()
    {
        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
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(APIUrl.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(httpClient.build())
                .build();
        //Toast.makeText(MyAppointmentActivity.this, selected_date + " selected!", Toast.LENGTH_SHORT).show();

        APIService service = retrofit.create(APIService.class);
        Call<InProgress_Response> call = service.getViewComplaintHistory(id);
        call.enqueue(new Callback<InProgress_Response>()
        {
            @Override
            public void onResponse(Call<InProgress_Response> call, Response<InProgress_Response> response)
            {
                if (response.isSuccessful()) {
                    List<SetterViewComplaintDetails> datumList1 = response.body().getData();


                    recyclerAdapter = new RecyclerViewComplaintAdapter(datumList1, getApplicationContext());
                    RecyclerView.LayoutManager recyce = new LinearLayoutManager(getApplicationContext());

                    recyclerView.setLayoutManager(recyce);
                    recyclerView.setItemAnimator(new DefaultItemAnimator());
                    recyclerView.setAdapter(recyclerAdapter);
                    recyclerAdapter.notifyDataSetChanged();

                }
            }
            @Override
            public void onFailure(Call<InProgress_Response> call, Throwable t) {

            }
        });
    }
}
