package com.cpm.lorealbaautomation.dailyactivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.cpm.lorealbaautomation.BuildConfig;
import com.cpm.lorealbaautomation.Database.Lorealba_Database;
import com.cpm.lorealbaautomation.R;
import com.cpm.lorealbaautomation.constant.AlertandMessages;
import com.cpm.lorealbaautomation.constant.CommonFunctions;
import com.cpm.lorealbaautomation.constant.CommonString;
import com.cpm.lorealbaautomation.delegates.PrefHelper;
import com.cpm.lorealbaautomation.retrofit.PostApiForUpload;
import com.cpm.lorealbaautomation.retrofit.StringConverterFactory;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.RequestBody;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Objects;

import retrofit.Call;
import retrofit.Callback;
import retrofit.Response;
import retrofit.Retrofit;

public class ServiceActivity extends AppCompatActivity implements View.OnClickListener {
    SharedPreferences preferences;
    ImageView btn_is_present;
    Context context;
    String date, user_name;

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service);
        context = this;
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        if (!CommonFunctions.isTablet(this)) {
            toolbar.setTitleTextAppearance(this, R.style.changestext_sizefor_mobile);
        }

        setTitle("Export Database");

        //preference data
       preferences = PrefHelper.getPrefs(context);
        date = preferences.getString(CommonString.KEY_DATE, "");
        user_name = preferences.getString(CommonString.KEY_USERNAME, "");
        btn_is_present = (ImageView) findViewById(R.id.btn_is_present);
        btn_is_present.setOnClickListener(this);

    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == android.R.id.home) {
            finish();
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
        }

        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.btn_is_present) {
            showExportDialog();
            // restoreBackup();
        }
    }

    public void restoreBackup() {

        try {
            File sd = Environment.getExternalStorageDirectory();
            File data = Environment.getDataDirectory();

            if (sd.canWrite()) {
                String currentDBPath = "//data//" + BuildConfig.APPLICATION_ID + "//databases//" + Lorealba_Database.DATABASE_NAME;
                String backupDBPath = "shama.baLorealBa_BackupMar_22_21145440.db";
                File currentDB = new File(data, currentDBPath);
                File backupDB = new File(sd, backupDBPath);

                if (currentDB.exists()) {
                    FileChannel src = new FileInputStream(backupDB).getChannel();
                    FileChannel dst = new FileOutputStream(currentDB).getChannel();
                    dst.transferFrom(src, 0, src.size());
                    src.close();
                    dst.close();
                    Toast.makeText(getApplicationContext(), "Database Restored successfully", Toast.LENGTH_SHORT).show();
                }
            }
        } catch (Exception e) {
            //test(e.getMessage());
        }
    }

    public void showExportDialog() {
        android.app.AlertDialog.Builder builder1 = new android.app.AlertDialog.Builder(context).setTitle(R.string.dialog_title);
        builder1.setMessage(R.string.Areyou_sure_take_backup)
                .setCancelable(false)
                .setPositiveButton(R.string.ok, (dialog, id) -> {
                    try {
                        File sd = context.getExternalFilesDir("");
                        File data = Environment.getDataDirectory();
                        assert sd != null;
                        if (sd.canWrite()) {
                            long date = System.currentTimeMillis();
                            @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("MMM/dd/yy");
                            String dateString = sdf.format(date);
                            String currentDBPath = "//data//" + BuildConfig.APPLICATION_ID + "//databases//" + Lorealba_Database.DATABASE_NAME;
                            String backupDBPath = user_name + CommonString.BACKUP_FOLDER_NAME + dateString.replace('/', '_') + CommonFunctions.getCurrentTime_only().replace(":", "") + ".db";
                            String path = CommonString.getBackupFolder(context);
                            File currentDB = new File(data, currentDBPath);
                            File backupDB = new File(path, backupDBPath);
                            if (currentDB.exists()) {
                                @SuppressWarnings("resource")
                                FileChannel src = new FileInputStream(currentDB).getChannel();
                                FileChannel dst = new FileOutputStream(backupDB).getChannel();
                                dst.transferFrom(src, 0, src.size());
                                src.close();
                                dst.close();
                            }

                            File dir = new File(CommonString.getBackupFolder(context));
                            ArrayList<String> list;
                            list = getFileNames(Objects.requireNonNull(dir.listFiles()));
                            if (!list.isEmpty()) {
                                for (int i1 = 0; i1 < list.size(); i1++) {
                                    if (list.get(i1).contains(CommonString.BACKUP_FOLDER_NAME)) {
                                        File originalFile = new File(CommonString.getBackupFolder(context) + list.get(i1));
                                        uploadBackup(context, originalFile.getName(), "DBBackup");
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.fillInStackTrace();
                        AlertandMessages.showAlert((Activity) context, context.getString(R.string.errordatabase_not_exporting), true);
                    }
                }).setNegativeButton(android.R.string.cancel, (dialog, id) -> dialog.cancel());
        AlertDialog alert1 = builder1.create();
        alert1.show();
    }


    public ArrayList<String> getFileNames(File[] file) {
        ArrayList<String> arrayFiles = new ArrayList<String>();
        if (file.length > 0) {
            for (File value : file) arrayFiles.add(value.getName());
        }

        return arrayFiles;
    }

    public static void uploadBackup(final Context context, String file_name, String folder_name) {
        RequestBody body1;
        final File originalFile = new File(CommonString.getBackupFolder(context) + file_name);
        RequestBody photo = RequestBody.create(MediaType.parse("application/octet-stream"), originalFile);
        body1 = new MultipartBuilder().type(MultipartBuilder.FORM).addFormDataPart("file", originalFile.getName(), photo).addFormDataPart("Foldername", folder_name).addFormDataPart("Path", "1111111").build();
        Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URLGORIMAG).addConverterFactory(new StringConverterFactory()).build();
        PostApiForUpload api = adapter.create(PostApiForUpload.class);
        Call<String> call = api.getUploadImageRetrofitOne(body1);
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Response<String> response) {
                String responseBody = response.body();
                if (responseBody != null && response.isSuccess()) {
                    if (response.body().contains(CommonString.KEY_SUCCESS)) {
                        try {
                            originalFile.delete();
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                        AlertandMessages.showToastMsg(context, "Database Exported And Uploaded Successfully");
                    }
                }
            }

            @Override
            public void onFailure(Throwable t) {
                AlertandMessages.showToastMsg(context, originalFile.getName() + " not uploaded");
            }
        });
    }

}
