package com.example.mynotepad.Dialogs.FoldersCustomDialog;

import android.app.Activity;
import android.app.Dialog;
import android.graphics.drawable.ColorDrawable;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.mynotepad.MainActivity;
import com.example.mynotepad.R;

import java.util.ArrayList;

public class CreateNewFolderDialog {
    private TextView cancel , done;
    private EditText folderName;
    private Activity activity;

    public void showDialog(Activity activity){
        this.activity = activity;
        Dialog dialog = new Dialog(activity);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        dialog.setCancelable(true);
        dialog.setContentView(R.layout.dialog_create_new_folder);
        cancel = dialog.findViewById(R.id.cancel);
        done = dialog.findViewById(R.id.done);
        folderName = dialog.findViewById(R.id.folderName);
        addListener(dialog);
        dialog.show();
    }

    private void addListener(final Dialog dialog) {
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        done.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (folderNameIsAcceptable(folderName.getText().toString())) {
                    //save new folder in sharedPreferences
                    ArrayList<String> foldersArray = MainActivity.sharedPreferencesClass.getArrayFolders(activity,"folders");
                    if (foldersArray == null)// if it is the first folder we are creating this  array will be null
                        foldersArray = new ArrayList<>();
                    foldersArray.add(folderName.getText().toString());
                    MainActivity.sharedPreferencesClass.saveArrayFolders(activity ,foldersArray , "folders");
                    dialog.dismiss();
                }
            }
        });
    }

    private boolean folderNameIsAcceptable(String newFolderName) {
        if (!newFolderName.equals("")){
            ArrayList<String> foldersArray = MainActivity.sharedPreferencesClass.getArrayFolders(activity,"folders");
            if (foldersArray == null)return true;//if it is first time we wanna create a folder no need to check being unique
            for (String folderName : foldersArray){
                if (folderName.equals(newFolderName)) {
                    Toast.makeText(activity , "this folder already exists" , Toast.LENGTH_SHORT).show();
                    return false;
                }
            }
            return true;
        }
        Toast.makeText(activity ,"you should enter a name to create new folder",Toast.LENGTH_SHORT).show();
        return false;
    }

}
