/*
 * @author Javier Martin Manzano
 */

package ub.incendishab;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.OpenableColumns;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;

import android.database.Cursor;

public class Home extends AppCompatActivity {

    public static final int SELECT_FILE = 1;

    private Boolean edit = false;

    private Activity thisActivity;

    private View.OnClickListener goToBuilderListener = new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(thisActivity,Builder.class);
            startActivity(intent);
        }
    };

    private View.OnClickListener loadBuildingListener = new View.OnClickListener(){
        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public void onClick(View v) {
            selectFile();
        }
    };

    private View.OnClickListener editBuildingListener = new View.OnClickListener(){
        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public void onClick(View v) {
            edit = true;
            selectFile();
        }
    };

    private View.OnClickListener configurationListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(thisActivity,Configuration.class);
            startActivity(intent);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        thisActivity = this;
        setContentView(R.layout.activity_home);
        Button button = findViewById(R.id.createBuildingButton);
        button.setOnClickListener(goToBuilderListener);
        Button button2 = findViewById(R.id.loadBuildingButton);
        button2.setOnClickListener(loadBuildingListener);
        Button button3 = findViewById(R.id.editBuildingButton);
        button3.setOnClickListener(editBuildingListener);
        Button button4 = findViewById(R.id.configurationButton);
        button4.setOnClickListener(configurationListener);

        boolean permissions = grantPermissions();
        if (!permissions){
            finish();
        }
    }

    private void selectFile(){
        try{
            Intent pickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
            pickerIntent.setType("*/*");
            startActivityForResult(pickerIntent, SELECT_FILE);
        } catch (Exception ex){
            Log.i("Error ","Exception:" + ex.toString());
        }
    }


    @TargetApi(Build.VERSION_CODES.KITKAT)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode,resultCode,data);
        switch(requestCode){
            case SELECT_FILE:
                if(resultCode == RESULT_OK) {
                    String direccion = getFileNameFromUri(data);
                    if (!edit) {
                        Intent intent = new Intent(thisActivity, Building.class);
                        intent.putExtra("loadAll", true);
                        intent.putExtra("direccion", direccion);
                        startActivity(intent);
                    } else {
                        edit = false;
                        DataManager dataManager = new DataManager(direccion);
                        ArrayList<Object> a = dataManager.returnData();
                        Intent intent = new Intent(thisActivity, Builder.class);
                        intent.putExtra("plantas", (int) a.get(0));
                        intent.putExtra("viviendas", (int) a.get(1));
                        intent.putExtra("direccion", (String) a.get(2));
                        intent.putExtra("escaleras", (int) a.get(3));
                        intent.putExtra("ascensores",(int)a.get(4));
                        intent.putExtra("formato",(int)a.get(5));
                        intent.putExtra("entresuelo",(boolean) a.get(6));
                        intent.putExtra("bajos",(boolean)a.get(7));
                        intent.putExtra("atico",(boolean)a.get(8));
                        intent.putExtra("sotanos",(int)a.get(9));
                        startActivity(intent);
                    }
                }
        }
    }

    private String getFileNameFromUri(Intent data) {
        String[] strings = new String[1];
        Uri selectedFile = data.getData();
        if (selectedFile != null) {
            Cursor cursor = getContentResolver().query(selectedFile, null, null, null, null);
            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
            String selectedFilePath = cursor.getString(idx);
            cursor.close();
            strings = selectedFilePath.split("\\.");
        }
        return strings[0];
    }

    private boolean grantPermissions(){
        boolean perm = false;
        int permissionCheck = ContextCompat.checkSelfPermission(thisActivity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
            perm = true;
        } else {
            ActivityCompat.requestPermissions(thisActivity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                perm = true;
            }
        }
        return perm;
    }
}
