/*
 * @author Javier Martin Manzano
 */

package ub.incendishab;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.LightingColorFilter;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.OpenableColumns;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.DragEvent;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

public class Building extends AppCompatActivity {

    private Activity thisActivity;

    NavigationView navView;

    private DataManager dataManager;

    private static final int ACTIVITY_APARTMENT_FINISHED = 1;
    private static final int ACTIVITY_AREA_FINISHED = 2;

    private static final int SELECT_FILE = 5;

    private static final int CAPT_TIME = 600*1000;

    private int xOffsetText;
    private int yOffsetText;

    private int xOffsetPerson;
    private int yOffsetPerson;
    private int xOffsetPersonToPerson;

    private int xOffsetMini;
    private int yOffsetMini;
    private int xOffsetMiniToPerson;

    private Bot bot;

    private float[] fingerCoords = new float[2];
    private int plantas;
    private int vivPorPlanta;

    private int alturaTotal;
    private int longitudTotal;

    private float zoom = 1f;
    private ArrayList<String> direcciones;
    private int direccionIndex;
    private int escaleras,ascensores,sotanos;
    private boolean entresuelo,bajos,atico;
    private int formato;

    private int escalera;

    private Canvas[][][] canvasMatrix;
    private Bitmap[][][] bitmapMatrix;
    private ImageView[][][] imageViewMatrix;

    private Paint paint,paintText;

    private String hospital;
    private boolean dragFromCanvas = false;
    private boolean menuMode = false;
    private int[] menuCoords, dragCoords;

    private Timer timer;


    private SeekBar.OnSeekBarChangeListener seekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (progress > 0){
                zoom = progress*0.2f;
            } else {
                zoom = 0.1f;
            }
            int width = BitmapFactory.decodeResource(thisActivity.getResources(),R.drawable.piso).getWidth();
            int height = BitmapFactory.decodeResource(thisActivity.getResources(),R.drawable.piso).getHeight();
            for (int esc=0;esc<dataManager.getEscaleras();esc++) {
                for (int i = 0; i < alturaTotal; i++) {
                    for (int j = 0; j < longitudTotal; j++) {
                        imageViewMatrix[esc][i][j].getLayoutParams().width = (int) (width * zoom);
                        imageViewMatrix[esc][i][j].getLayoutParams().height = (int) (height * zoom);
                        imageViewMatrix[esc][i][j].invalidate();
                        imageViewMatrix[esc][i][j].requestLayout();
                    }
                }
            }
        }
        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {}
        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {}
    };

    private View.OnClickListener sendImageListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.i("SendPhoto","Sending photo...");
            sendPhoto();
            Log.i("SendText","Sending text...");
            sendSummaryText();
        }
    };

    private View.OnClickListener sendDetailListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.i("SendText","Sending text...");
            sendDetailText();
        }
    };

    private View.OnClickListener returnListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            timer.cancel();
            thisActivity.finish();
        }
    };

    private View.OnClickListener addBuildingListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            selectFile();
        }
    };

    private View.OnClickListener nextBuildingListener = new View.OnClickListener() {
        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public void onClick(View v) {
            if (direcciones.size()>1){
                direccionIndex++;
                if (direccionIndex == direcciones.size()){
                    direccionIndex = 0;
                }
                reloadAddress();
            }
        }
    };

    private TimerTask task = new TimerTask() {
        @Override
        public void run() {
            sendImageListener.onClick(findViewById(R.id.sendImageButton));
        }
    };

    private DrawerLayout.DrawerListener drawerListener = new DrawerLayout.DrawerListener() {
        @Override
        public void onDrawerSlide(@NonNull View view, float v) {

        }

        @Override
        public void onDrawerOpened(@NonNull View view) {

        }

        @Override
        public void onDrawerClosed(@NonNull View view) {
            menuMode = false;
            drawPeopleInApartment(menuCoords[0], menuCoords[1], escalera);
        }

        @Override
        public void onDrawerStateChanged(int i) {

        }
    };

    private NavigationView.OnNavigationItemSelectedListener itemSelectedListener = new NavigationView.OnNavigationItemSelectedListener(){
      @RequiresApi(api = Build.VERSION_CODES.KITKAT)
      @Override
      public boolean onNavigationItemSelected(MenuItem menuItem){
          String estado = dataManager.readState(menuCoords[0], menuCoords[1], escalera);
          switch (menuItem.getItemId()) {
              case R.id.fire:
                  if ((menuItem.getTitle().toString()).equals("FUEGO: ORIGEN")){
                      menuItem.setTitle("FUEGO: NO");
                      estado = estado.replace("origen","");
                      if (estado.isEmpty()){
                          estado = estado.concat("normal");
                      }
                  } else if ((menuItem.getTitle().toString()).equals("FUEGO: SI")){
                      menuItem.setTitle("FUEGO: ORIGEN");
                      estado = estado.replace("afectado","origen");
                  } else if ((menuItem.getTitle().toString()).equals("FUEGO: NO")){
                      menuItem.setTitle("FUEGO: SI");
                      if (estado.contains("normal")){
                          estado = estado.replace("normal","afectado");
                      } else {
                          estado = estado.concat(" afectado");
                      }
                  }
                  break;

              case R.id.smoke:
                  if ((menuItem.getTitle().toString()).equals("HUMO: SI")){
                      menuItem.setTitle("HUMO: NO");
                      estado = estado.replace("humo","");
                      if (estado.isEmpty()){
                          estado = estado.concat("normal");
                      }
                      dataManager.setState(menuCoords[0],menuCoords[1],estado, escalera);
                  } else if ((menuItem.getTitle().toString()).equals("HUMO: NO")){
                      menuItem.setTitle("HUMO: SI");
                      if (estado.contains("normal")){
                          estado = estado.replace("normal","humo");
                      } else {
                          estado = estado.concat(" humo");
                      }
                  }
                  break;

              case R.id.structural:
                  if ((menuItem.getTitle().toString()).equals("ESTRUCTURAL: SI")){
                      menuItem.setTitle("ESTRUCTURAL: NO");
                      estado = estado.replace("estructural","");
                      if (estado.isEmpty())
                          estado = estado.concat("normal");
                  } else if ((menuItem.getTitle().toString()).equals("ESTRUCTURAL: NO")){
                      menuItem.setTitle("ESTRUCTURAL: SI");
                      if (estado.contains("normal")){
                          estado = estado.replace("normal","estructural");
                      } else {
                          estado = estado.concat(" estructural");
                      }
                  }
                  break;

              case R.id.dontExist:
                  if ((menuItem.getTitle().toString()).equals("EXISTE")){
                      menuItem.setTitle("NO EXISTE");
                      estado = "no_existe";
                      navView.getMenu().findItem(R.id.fire).setTitle("FUEGO: NO");
                      navView.getMenu().findItem(R.id.fire).setEnabled(false);
                      navView.getMenu().findItem(R.id.smoke).setTitle("HUMO: NO");
                      navView.getMenu().findItem(R.id.smoke).setEnabled(false);
                      navView.getMenu().findItem(R.id.structural).setTitle("ESTRUCTURAL: NO");
                      navView.getMenu().findItem(R.id.structural).setEnabled(false);
                  } else if ((menuItem.getTitle().toString()).equals("NO EXISTE")){
                      menuItem.setTitle("EXISTE");
                      estado = "normal";
                      navView.getMenu().findItem(R.id.fire).setEnabled(true);
                      navView.getMenu().findItem(R.id.smoke).setEnabled(true);
                      navView.getMenu().findItem(R.id.structural).setEnabled(true);
                  }
                  break;

              case R.id.editPeople:
                  Intent intent = new Intent(thisActivity,Area.class);
                  intent.putExtra("direccion",direcciones.get(direccionIndex));
                  intent.putExtra("altura",menuCoords[0]);
                  intent.putExtra("longitud",menuCoords[1]);
                  intent.putExtra("escalera", escalera);
                  startActivityForResult(intent, ACTIVITY_APARTMENT_FINISHED);
                  break;

              case R.id.inspected:
                  if ((menuItem.getTitle().toString()).equals("REVISADO: NO")){
                      menuItem.setTitle("REVISADO: SI");
                      dataManager.setInspected(menuCoords[0], menuCoords[1], escalera, true);
                  } else if ((menuItem.getTitle().toString()).equals("REVISADO: SI")){
                      menuItem.setTitle("REVISADO: NO");
                      dataManager.setInspected(menuCoords[0], menuCoords[1], escalera, false);
                  }
                  break;

              default:
                  break;

          }
          dataManager.setState(menuCoords[0], menuCoords[1],estado, escalera);
          drawPeopleInApartment(menuCoords[0], menuCoords[1], escalera);
          return true;
        }
    };


    @RequiresApi(Build.VERSION_CODES.KITKAT)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case ACTIVITY_APARTMENT_FINISHED:
                if (resultCode == RESULT_OK) {
                    dataManager = new DataManager(direcciones.get(direccionIndex));
                    drawPeopleInApartment(menuCoords[0],menuCoords[1], escalera);
                    reDrawEvac();
                    reDrawHosp();
                }
                break;
            case ACTIVITY_AREA_FINISHED:
                if (resultCode == RESULT_OK) {
                    dataManager = new DataManager(direcciones.get(direccionIndex));
                    reDrawEvac();
                    reDrawHosp();
                }
                break;
            case SELECT_FILE:
                if(resultCode == RESULT_OK) {
                    String direccion = getFileNameFromUri(data);
                    if (!direcciones.contains(direccion)){
                        direccionIndex++;
                        direcciones.add(direccion);
                        reloadAddress();
                    } else {
                        Toast.makeText(thisActivity, "El edificio seleccionado ya está cargado",Toast.LENGTH_LONG).show();
                    }
                }
                break;
        }
    }

    private View.OnClickListener onClickListenerArea = new View.OnClickListener() {
        @Override
        public void onClick(View v){
            Intent intent = new Intent(thisActivity,Area.class);
            if (v.getId()==R.id.evacView){
                intent.putExtra("evac",true);
            } else if (v.getId()==R.id.hospView){
                intent.putExtra("hosp",true);
            }
            intent.putExtra("direccion",direcciones.get(direccionIndex));
            startActivityForResult(intent, ACTIVITY_AREA_FINISHED);
        }
    };

    private View.OnTouchListener onTouchListenerPerson = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent ev){
            ClipData data = ClipData.newPlainText("personType", (v.getResources().getResourceName(v.getId())).replace("View", "").replace("ub.incendishab:id/", ""));
            data.addItem(new ClipData.Item("1"));
            v.startDrag(data, new View.DragShadowBuilder(v), null, 0);
            return true;
        }
    };

    private View.OnLongClickListener onLongClickListenerCanvas = new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            if (menuMode) {
                drawPeopleInApartment(menuCoords[0],menuCoords[1], escalera);
            } else {
                menuMode = true;

                menuCoords = findElementInMatrix((ImageView)v);
                String im = dataManager.readImage(menuCoords[0], menuCoords[1], escalera);
                int id = thisActivity.getResources().getIdentifier(im, "drawable", thisActivity.getPackageName());
                int anchura = BitmapFactory.decodeResource(thisActivity.getResources(), id).getWidth();
                int altura = BitmapFactory.decodeResource(thisActivity.getResources(), id).getHeight();

                drawPeopleInApartment(menuCoords[0], menuCoords[1], escalera);
                HorizontalScrollView canvasHSV = findViewById(R.id.canvasHScrollView);
                ScrollView canvasVSV = findViewById(R.id.canvasVScrollView);


                int x = (int) (menuCoords[1] * anchura * zoom + (anchura * zoom / 2) - (canvasHSV.getWidth() / 2));
                int y = (int) (menuCoords[0] * altura * zoom + (altura * zoom / 2) - (canvasHSV.getHeight() / 2));
                if (escalera==2) {
                    x += dataManager.getLongitudTotal()*anchura*zoom;
                }

                canvasHSV.smoothScrollTo(x , y);
                canvasVSV.smoothScrollTo(x, y);
                ((DrawerLayout) findViewById(R.id.drawer_layout)).openDrawer(Gravity.START);
                String estado = dataManager.readState(menuCoords[0], menuCoords[1], escalera);

                Boolean rev = dataManager.readInspected(menuCoords[0], menuCoords[1],escalera);

                navView.getMenu().findItem(R.id.fire).setTitle("FUEGO: NO");
                navView.getMenu().findItem(R.id.fire).setCheckable(false);
                navView.getMenu().findItem(R.id.smoke).setTitle("HUMO: NO");
                navView.getMenu().findItem(R.id.smoke).setCheckable(false);
                navView.getMenu().findItem(R.id.structural).setTitle("ESTRUCTURAL: NO");
                navView.getMenu().findItem(R.id.structural).setCheckable(false);
                navView.getMenu().findItem(R.id.dontExist).setTitle("EXISTE");
                navView.getMenu().findItem(R.id.dontExist).setCheckable(false);
                navView.getMenu().findItem(R.id.inspected).setTitle("REVISADO: NO");
                navView.getMenu().findItem(R.id.inspected).setCheckable(false);
                navView.getMenu().findItem(R.id.fire).setEnabled(true);
                navView.getMenu().findItem(R.id.smoke).setEnabled(true);
                navView.getMenu().findItem(R.id.structural).setEnabled(true);
                navView.getMenu().findItem(R.id.inspected).setEnabled(true);
                navView.getMenu().findItem(R.id.editPeople).setCheckable(false);
                navView.getMenu().findItem(R.id.editPeople).setEnabled(true);

                if (estado.contains("afectado"))
                    navView.getMenu().findItem(R.id.fire).setTitle("FUEGO: SI");
                else if (estado.contains("origen"))
                    navView.getMenu().findItem(R.id.fire).setTitle("FUEGO: ORIGEN");
                if (estado.contains("estructural"))
                    navView.getMenu().findItem(R.id.structural).setTitle("ESTRUCTURAL: SI");
                if (estado.contains("humo"))
                    navView.getMenu().findItem(R.id.smoke).setTitle("HUMO: SI");
                if (estado.contains("no_existe")) {
                    navView.getMenu().findItem(R.id.dontExist).setTitle("NO_EXISTE");
                    navView.getMenu().findItem(R.id.fire).setEnabled(false);
                    navView.getMenu().findItem(R.id.smoke).setEnabled(false);
                    navView.getMenu().findItem(R.id.structural).setEnabled(false);
                }
                if (rev){
                    navView.getMenu().findItem(R.id.inspected).setTitle("REVISADO: SI");
                }
            }
            return true;
        }
    };

    private View.OnTouchListener onTouchListenerCanvas = new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent ev){
            fingerCoords[0] = ev.getX()/zoom;
            fingerCoords[1] = ev.getY()/zoom;
            int[] elementCoords = findElementInMatrix((ImageView)v);

            if (!menuMode) {
                int action = (ev.getAction() & MotionEvent.ACTION_MASK);
                switch (action){
                    case MotionEvent.ACTION_POINTER_DOWN:
                        break;

                    case MotionEvent.ACTION_DOWN:
                        boolean personExists = false;
                        int personTypes = dataManager.confInApartment(elementCoords[0], elementCoords[1], escalera);

                        String personType = null;
                        int quant = 0;
                        View view = null;
                        //int index = 0;
                        Bitmap bm = BitmapFactory.decodeResource(thisActivity.getResources(),R.drawable.personokcard);

                        for (int i = 0; i < personTypes; i++) {
                            if (dataManager.readConfQuant(elementCoords[0],elementCoords[1],i, escalera)>0){
                                if (fingerCoords[0] >= (xOffsetPerson + (i * xOffsetPersonToPerson)) && fingerCoords[1] >= (yOffsetPerson) && fingerCoords[0] <= (xOffsetPerson + (i * xOffsetPersonToPerson) + bm.getWidth()) && fingerCoords[1] <= (yOffsetPerson + bm.getHeight())) {
                                    personExists = true;
                                    dragCoords = elementCoords;
                                    if (i == 1) {
                                        personType = "z4";
                                    } else if (i == 2) {
                                        personType = "z5";
                                    } else if (i == 3) {
                                        personType = "z6";
                                    } else {
                                        personType = "person";
                                    }

                                    quant = dataManager.readConfQuant(elementCoords[0], elementCoords[1], i, escalera);
                                    //index = i;
                                    switch (i) {
                                        case 0:
                                            view = findViewById(R.id.okView);
                                            break;
                                        case 1:
                                            view = findViewById(R.id.z4View);
                                            break;
                                        case 2:
                                            view = findViewById(R.id.z5View);
                                            break;
                                        case 3:
                                            view = findViewById(R.id.z6View);
                                            break;
                                        default:
                                            break;
                                    }
                                }
                            }
                        }
                        //Si estoy pulsando sobre una persona
                        if (personExists) {
                            ClipData data = ClipData.newPlainText("persontype", personType);
                            data.addItem(new ClipData.Item(Integer.toString(quant)));
                            v.startDrag(data, new View.DragShadowBuilder(view), null, 0);
                            dataManager.removePerson(elementCoords[0], elementCoords[1], escalera, personType);
                            drawPeopleInApartment(elementCoords[0], elementCoords[1], escalera);
                            dragFromCanvas = true;
                            return true;
                        }
                        break;

                    default:
                        break;
                }

            }
            return false;
        }
    };

    private View.OnDragListener onDragListenerCanvas = new View.OnDragListener() {
        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public boolean onDrag(View v, DragEvent ev){
            final int action = ev.getAction();
            int coords[];
            switch (action){
                case DragEvent.ACTION_DRAG_STARTED:
                    return true;

                case DragEvent.ACTION_DRAG_ENTERED:
                    ((ImageView)v).setColorFilter(Color.LTGRAY, PorterDuff.Mode.LIGHTEN);
                    return true;

                case DragEvent.ACTION_DRAG_LOCATION:
                    return true;

                case DragEvent.ACTION_DRAG_EXITED:
                    ((ImageView)v).setColorFilter(Color.TRANSPARENT);
                    return true;

                case DragEvent.ACTION_DROP:
                    ((ImageView)v).setColorFilter(Color.TRANSPARENT);
                    String personType = ev.getClipData().getItemAt(0).getText().toString();
                    int quant = Integer.parseInt(ev.getClipData().getItemAt(1).getText().toString());
                    coords = findElementInMatrix((ImageView)v);
                    if (dragFromCanvas){
                        dataManager.addConfPerson(coords[0], coords[1], escalera);
                    } else {
                        dataManager.addConfPerson(coords[0], coords[1], personType, quant, escalera);
                    }
                    drawPeopleInApartment(coords[0], coords[1], escalera);
                    dragFromCanvas = false;
                    return true;

                case DragEvent.ACTION_DRAG_ENDED:
                    if (dragFromCanvas) {
                        coords = findElementInMatrix((ImageView)v);
                        dataManager.addConfPerson(coords[0], coords[1], escalera);
                        drawPeopleInApartment(dragCoords[0],dragCoords[1], escalera);
                        dragFromCanvas = false;
                    }
                    return true;

                default:
                    break;
            }
            return false;
        }
    };

    private View.OnDragListener onDragListenerArea = new View.OnDragListener() {
        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public boolean onDrag(View v, DragEvent ev){
            final int action = ev.getAction();
            switch (action){
                case DragEvent.ACTION_DRAG_STARTED:
                    return true;

                case DragEvent.ACTION_DRAG_ENTERED:
                    ((ImageView)v).setColorFilter(Color.LTGRAY, PorterDuff.Mode.LIGHTEN);
                    return true;

                case DragEvent.ACTION_DRAG_LOCATION:
                    return true;

                case DragEvent.ACTION_DRAG_EXITED:
                    ((ImageView)v).setColorFilter(Color.TRANSPARENT);
                    return true;

                case DragEvent.ACTION_DROP:
                    ((ImageView)v).setColorFilter(Color.TRANSPARENT);
                    if (dragFromCanvas) {
                        if (v.getId()==R.id.evacView) {
                            dataManager.addEvacPerson(dragCoords[0],dragCoords[1], escalera);
                            drawPeopleInApartment(dragCoords[0],dragCoords[1], escalera);
                            reDrawEvac();
                        } else if (v.getId()==R.id.hospView) {
                            addHospitalText();
                        }
                        dragFromCanvas = false;
                    }
                    return true;

                case DragEvent.ACTION_DRAG_ENDED:
                    return true;

                default:
                    break;
            }
            return false;
        }
    };

    private View.OnDragListener onDragListenerPerson = new View.OnDragListener() {
        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public boolean onDrag(View v, DragEvent ev){
            final int action = ev.getAction();
            switch (action){
                case DragEvent.ACTION_DRAG_STARTED:
                    return true;

                case DragEvent.ACTION_DRAG_ENTERED:
                    return true;

                case DragEvent.ACTION_DRAG_LOCATION:
                    return true;

                case DragEvent.ACTION_DRAG_EXITED:
                    return true;

                case DragEvent.ACTION_DROP:
                    dragFromCanvas = false;
                    reDrawEvac();
                    reDrawHosp();
                    return true;

                case DragEvent.ACTION_DRAG_ENDED:
                    return true;

                default:
                    break;
            }
            return false;
        }
    };



    private void sendPhoto (){
        String text;
        File imageFile = new File(Environment.getExternalStorageDirectory().getPath()+"/buildingcapture.jpg");

        byte[] byteArray;
        ByteArrayOutputStream stream;
        int width = dataManager.getLongitudTotal()*bitmapMatrix[0][0][0].getWidth()*dataManager.getEscaleras();
        int height = dataManager.getAlturaTotal()*bitmapMatrix[0][0][0].getHeight();

        Bitmap finalBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        for(int i=0;i<dataManager.getLongitudTotal();i++) {
            for (int esc=0;esc<dataManager.getEscaleras();esc++) {
                for (int j = 0; j < dataManager.getAlturaTotal(); j++) {
                    int[] tilePixels = new int[bitmapMatrix[0][0][0].getWidth() * bitmapMatrix[0][0][0].getHeight()];
                    bitmapMatrix[esc][j][i].getPixels(tilePixels, 0, bitmapMatrix[0][0][0].getWidth(), 0, 0, bitmapMatrix[0][0][0].getWidth(), bitmapMatrix[0][0][0].getHeight());
                    finalBitmap.setPixels(tilePixels, 0, bitmapMatrix[0][0][0].getWidth(), (i+esc*dataManager.getLongitudTotal()) * bitmapMatrix[0][0][0].getWidth(), j * bitmapMatrix[0][0][0].getHeight(), bitmapMatrix[0][0][0].getWidth(), bitmapMatrix[0][0][0].getHeight());
                }
            }
        }
        stream = new ByteArrayOutputStream();
        finalBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        byteArray = stream.toByteArray();

        try {
            imageFile.createNewFile();
            FileOutputStream fos = new FileOutputStream(imageFile);
            fos.write(byteArray);
        } catch (Exception e) {
            Log.e("Error--------->", e.toString());
        }

        if (finalBitmap.getHeight()/2>2560 || finalBitmap.getWidth()/2>2560){
            bot.sendDocumentRequest(imageFile, direcciones.get(direccionIndex));
        } else {
            bot.sendPhotoRequest(imageFile, direcciones.get(direccionIndex));
        }
        while (bot.getResponse().isEmpty()) {}
        if (bot.getResponse().startsWith("SendResponse")) {
            text = "Enviada imagen.";
            Toast.makeText(thisActivity, "Imagen enviada",Toast.LENGTH_LONG).show();
        } else {
            text = "Excepción: " + bot.getResponse();
            Toast.makeText(thisActivity, "Error enviando imagen. ¿Hay acceso a Internet?",Toast.LENGTH_LONG).show();
        }
        Log.i("SendPhotoResponse",text);
        bot.deleteResponse();
    }

    private void sendSummaryText(){
        String text;
        String message = "Confinados: "+dataManager.getConfinados();
        message = message.concat("\nEvacuados: "+dataManager.getEvacuados());
        message = message.concat("\nHospitalizados: "+dataManager.getHospitalizados());
        message = message.concat("\nAfectaciones estructurales: "+dataManager.getAfectEstructurales());
        message = message.concat("\nAfectaciones de humo: "+dataManager.getAfectHumo());
        message = message.concat("\nAfectaciones de fuego: "+dataManager.getAfectFuego());
        message = message.concat("\nAfectaciones de origen de fuego: "+dataManager.getAfectOrigen());
        message = message.concat("\nZonas revisadas: "+dataManager.getRevisados());
        message = message.concat("\nZonas no revisadas: "+dataManager.getNoRevisados());

        bot.sendMessageRequest(message);

        while (bot.getResponse().isEmpty()){ }
        if (bot.getResponse().startsWith("SendResponse")){
            text = "Enviado texto: \n\n"+message;
            Toast.makeText(thisActivity, "Enviado resumen", Toast.LENGTH_LONG).show();
        } else {
            text = "Excepción: "+bot.getResponse();
            Toast.makeText(thisActivity, "Error enviando resumen. ¿Hay acceso a Internet?",Toast.LENGTH_LONG).show();
        }
        Log.i("SendSummaryTextResponse", text);
        bot.deleteResponse();
    }

    private void sendDetailText(){
        String text;
        String apartmentText;
        String message = direcciones.get(direccionIndex);
        if (dataManager.getAfectOrigen()+dataManager.getAfectFuego()+dataManager.getAfectHumo()+dataManager.getAfectEstructurales() > 0){
            message = message.concat("\n\nAfectaciones");
        }
        String estado;
        boolean afectaciones, personas;
        int conf[] = new int[4];
        int evac[] = new int[4];
        int hosp[] = new int[4];

        for (int esc=1;esc<dataManager.getEscaleras()+1;esc++){
            for (int a=0;a<dataManager.getAlturaTotal();a++) {
                for (int l = 0; l < dataManager.getLongitudTotal(); l++) {
                    estado = dataManager.readState(a, l, esc);
                    afectaciones = false;
                    if (!estado.equals("normal") && !estado.equals("no_existe")) {
                        apartmentText = dataManager.readText(a, l, esc);
                        if (apartmentText.isEmpty()) {
                            apartmentText = dataManager.readImage(a, l, esc);
                            apartmentText = apartmentText.split("[1-3]")[0];
                        }
                        if (dataManager.getEscaleras()>1){
                            if (esc==1) {
                                apartmentText = apartmentText.concat(" escalera A");
                            } else if (esc==2) {
                                apartmentText = apartmentText.concat(" escalera B");
                            }
                        }
                        message = message.concat("\n" + apartmentText + ": ");
                        if (estado.contains("origen")) {
                            message = message.concat("Origen de fuego");
                            afectaciones = true;
                        } else if (estado.contains("afectado")) {
                            message = message.concat("Afectado por fuego");
                            afectaciones = true;
                        }
                        if (estado.contains("estructural")) {
                            if (afectaciones) {
                                message = message.concat(", afectación estructural");
                            } else {
                                message = message.concat("Afectación estructural");
                            }
                            afectaciones = true;
                        }
                        if (estado.contains("humo")) {
                            if (afectaciones) {
                                message = message.concat(", afectado por humo");
                            } else {
                                message = message.concat("Afectado por humo");
                            }
                        }
                    }
                }
            }
        }
        if (dataManager.getConfinados()+dataManager.getEvacuados()+dataManager.getHospitalizados() > 0){
            message = message.concat("\n\nPersonas");
        }
        for (int esc=1;esc<dataManager.getEscaleras()+1;esc++){
            for (int a=0;a<dataManager.getAlturaTotal();a++) {
                for (int l = 0; l < dataManager.getLongitudTotal(); l++) {
                    for (int type = 0; type < 4; type++) {
                        conf[type] = dataManager.readConfQuant(a, l, type, esc);
                        evac[type] = dataManager.readEvacQuant(a, l, type, esc);
                        hosp[type] = dataManager.readHospQuant(a, l, type, esc);
                    }
                    if (conf[0] + conf[1] + conf[2] + conf[3] + evac[0] + evac[1] + evac[2] + evac[3] + hosp[0] + hosp[1] + hosp[2] + hosp[3] > 0) {
                        apartmentText = dataManager.readText(a, l, esc);
                        if (apartmentText.isEmpty()) {
                            apartmentText = dataManager.readImage(a, l, esc);
                            apartmentText = apartmentText.split("[1-3]")[0];
                        }
                        if (dataManager.getEscaleras()>1){
                            if (esc==1) {
                                apartmentText = apartmentText.concat(" escalera A");
                            } else if (esc==2) {
                                apartmentText = apartmentText.concat(" escalera B");
                            }
                        }
                        message = message.concat("\n" + apartmentText + ": ");
                        if (conf[0] + conf[1] + conf[2] + conf[3] > 0) {
                            personas = false;
                            message = message.concat("\n   Confinados: ");
                            if (conf[0] > 0) {
                                message = message.concat(conf[0] + " sanos");
                                personas = true;
                            }
                            if (conf[1] > 0) {
                                if (personas) {
                                    message = message.concat(", ");
                                }
                                message = message.concat(conf[1] + " heridos leves");
                                personas = true;
                            }
                            if (conf[2] > 0) {
                                if (personas) {
                                    message = message.concat(", ");
                                }
                                message = message.concat(conf[2] + " heridos graves");
                                personas = true;
                            }
                            if (conf[3] > 0) {
                                if (personas) {
                                    message = message.concat(", ");
                                }
                                message = message.concat(conf[3] + " muertos");
                            }
                        }
                        if (evac[0] + evac[1] + evac[2] + evac[3] > 0) {
                            personas = false;
                            message = message.concat("\n   Evacuados: ");
                            if (evac[0] > 0) {
                                message = message.concat(evac[0] + " sanos");
                                personas = true;
                            }
                            if (evac[1] > 0) {
                                if (personas) {
                                    message = message.concat(", ");
                                }
                                message = message.concat(evac[1] + " heridos leves");
                                personas = true;
                            }
                            if (evac[2] > 0) {
                                if (personas) {
                                    message = message.concat(", ");
                                }
                                message = message.concat(evac[2] + " heridos graves");
                                personas = true;
                            }
                            if (evac[3] > 0) {
                                if (personas) {
                                    message = message.concat(", ");
                                }
                                message = message.concat(evac[3] + " muertos");
                            }
                        }
                        if (hosp[0] + hosp[1] + hosp[2] + hosp[3] > 0) {
                            personas = false;
                            message = message.concat("\n   Hospitalizados: ");
                            if (hosp[0] > 0) {
                                message = message.concat(hosp[0] + " sanos");
                                personas = true;
                            }
                            if (hosp[1] > 0) {
                                if (personas) {
                                    message = message.concat(", ");
                                }
                                message = message.concat(hosp[1] + " heridos leves");
                                personas = true;
                            }
                            if (hosp[2] > 0) {
                                if (personas) {
                                    message = message.concat(", ");
                                }
                                message = message.concat(hosp[2] + " heridos graves");
                                personas = true;
                            }
                            if (hosp[3] > 0) {
                                if (personas) {
                                    message = message.concat(", ");
                                }
                                message = message.concat(hosp[3] + " muertos");
                            }
                        }
                    }

                }
            }
        }

        bot.sendMessageRequest(message);

        while (bot.getResponse().isEmpty()){ }
        if (bot.getResponse().startsWith("SendResponse")){
            text = "Enviado texto: \n\n"+message;
            Toast.makeText(thisActivity, "Enviado informe detallado", Toast.LENGTH_LONG).show();
        } else {
            text = "Excepción: "+bot.getResponse();
            Toast.makeText(thisActivity, "Error enviando informe detallado. ¿Hay acceso a Internet?",Toast.LENGTH_LONG).show();
        }
        Log.i("SendDetailTextResponse", text);
        bot.deleteResponse();
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        thisActivity = this;
        super.onCreate(savedInstanceState);
        bot = Bot.getBot();
        SharedPreferences preferences = getSharedPreferences("Prefs", Context.MODE_PRIVATE);
        String chatId = preferences.getString("chatId","-391609739");
        bot.setChatId(chatId);
        Bundle b = getIntent().getExtras();
        setContentView(R.layout.activity_building);
        navView = findViewById(R.id.navview);
        direccionIndex = 0;
        direcciones = new ArrayList<>();

        navView.setNavigationItemSelectedListener(itemSelectedListener);
        DrawerLayout drawer = (findViewById(R.id.drawer_layout));
        drawer.setScrimColor(Color.TRANSPARENT);
        drawer.addDrawerListener(drawerListener);

        //Cargar edificio
        if (b.containsKey("loadAll")){
            direcciones.add(b.getString("direccion"));
            dataManager = new DataManager(direcciones.get(direccionIndex));
            ArrayList<Object> a = dataManager.returnData();
            plantas = (int)a.get(0);
            vivPorPlanta = (int)a.get(1);
            escaleras = (int)a.get(3);
            ascensores = (int)a.get(4);
            formato = (int)a.get(5);
            entresuelo = (boolean) a.get(6);
            bajos = (boolean)a.get(7);
            atico = (boolean)a.get(8);
            sotanos = (int)a.get(9);

        //Editar edificio y crearlo de 0
        } else {
            boolean loadPeople = b.getBoolean("loadPeople");
            plantas = b.getInt("plantas");
            vivPorPlanta = b.getInt("viviendas");
            direcciones.add(b.getString("direccion"));
            escaleras = b.getInt("escaleras");
            ascensores = b.getInt("ascensores");
            entresuelo = b.getBoolean("entresuelo");
            bajos = b.getBoolean("bajos");
            atico = b.getBoolean("atico");
            sotanos = b.getInt("sotanos");
            formato = b.getInt("formato");
            dataManager = new DataManager(loadPeople,direcciones.get(direccionIndex),escaleras,plantas,vivPorPlanta,ascensores,formato,entresuelo,bajos,atico,sotanos);
        }

        paint = new Paint();
        paintText = new Paint();
        paintText.setTextSize(50.0f);
        paintText.setFakeBoldText(true);

        ImageView okView = findViewById(R.id.okView);
        ImageView z4View = findViewById(R.id.z4View);
        ImageView z5View = findViewById(R.id.z5View);
        ImageView z6View = findViewById(R.id.z6View);
        ImageView areaHosp = findViewById(R.id.hospView);
        ImageView areaEvac = findViewById(R.id.evacView);

        areaEvac.setOnDragListener(onDragListenerArea);
        areaHosp.setOnDragListener(onDragListenerArea);
        areaEvac.setOnClickListener(onClickListenerArea);
        areaHosp.setOnClickListener(onClickListenerArea);

        okView.setOnTouchListener(onTouchListenerPerson);
        z4View.setOnTouchListener(onTouchListenerPerson);
        z5View.setOnTouchListener(onTouchListenerPerson);
        z6View.setOnTouchListener(onTouchListenerPerson);

        okView.setOnDragListener(onDragListenerPerson);
        z4View.setOnDragListener(onDragListenerPerson);
        z5View.setOnDragListener(onDragListenerPerson);
        z6View.setOnDragListener(onDragListenerPerson);

        ((TextView)findViewById(R.id.addressText)).setText(direcciones.get(direccionIndex));
        Button button = findViewById(R.id.sendImageButton);
        button.setOnClickListener(sendImageListener);
        Button button2 = findViewById(R.id.returnButton);
        button2.setOnClickListener(returnListener);
        Button button3 = findViewById(R.id.sendDetailButton);
        button3.setOnClickListener(sendDetailListener);
        ImageButton button4 = findViewById(R.id.addBuildingButton);
        button4.setOnClickListener(addBuildingListener);
        ImageButton button5 = findViewById(R.id.nextBuildingButton);
        button5.setOnClickListener(nextBuildingListener);

        SeekBar seekBar = findViewById(R.id.zoomSeekBar);
        seekBar.setOnSeekBarChangeListener(seekBarChangeListener);

        setOffsets();

        drawNewBuilding();
        reDrawEvac();
        reDrawHosp();
        if (b.containsKey("loadAll") || b.getBoolean("loadPeople")){
            drawAllPeople();
        }
        timer = new Timer();
        timer.schedule(task,CAPT_TIME,CAPT_TIME);
    }

    private void drawAllPeople(){
        Log.i("building","Dibujando personas");

        for (int esc=1;esc<dataManager.getEscaleras()+1;esc++) {
            for (int i = 0; i < alturaTotal; i++) {
                for (int j = 0; j < longitudTotal; j++) {
                    drawPeopleInApartment(i, j, esc);
                }
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void drawNewBuilding(){

        Log.i("building","Construyendo edificio");

        longitudTotal = dataManager.getLongitudTotal();
        alturaTotal = dataManager.getAlturaTotal();

        LinearLayout vertLinearLayout = findViewById(R.id.verticalLayout);
        LinearLayout horLinearLayout;

        imageViewMatrix = new ImageView[dataManager.getEscaleras()][alturaTotal][longitudTotal];
        bitmapMatrix = new Bitmap[dataManager.getEscaleras()][alturaTotal][longitudTotal];
        canvasMatrix = new Canvas[dataManager.getEscaleras()][alturaTotal][longitudTotal];


        for (int i = 0; i < alturaTotal; i++) {
            horLinearLayout = new LinearLayout(this);
            horLinearLayout.setOrientation(LinearLayout.HORIZONTAL);
            vertLinearLayout.addView(horLinearLayout);
            for (int esc=0;esc<dataManager.getEscaleras();esc++) {
                for (int j = 0; j < longitudTotal; j++) {
                    imageViewMatrix[esc][i][j] = new ImageView(this);
                    imageViewMatrix[esc][i][j].setLongClickable(true);
                    imageViewMatrix[esc][i][j].setOnLongClickListener(onLongClickListenerCanvas);
                    imageViewMatrix[esc][i][j].setOnDragListener(onDragListenerCanvas);
                    imageViewMatrix[esc][i][j].setOnTouchListener(onTouchListenerCanvas);


                    horLinearLayout.addView(imageViewMatrix[esc][i][j]);
                    String im = dataManager.readImage(i, j, esc+1);
                    String text = dataManager.readText(i, j, esc+1);
                    int id = this.getResources().getIdentifier(im, "drawable", this.getPackageName());
                    Bitmap bm = BitmapFactory.decodeResource(this.getResources(), id);

                    bitmapMatrix[esc][i][j] = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), Bitmap.Config.ARGB_8888);
                    imageViewMatrix[esc][i][j].setImageBitmap(bitmapMatrix[esc][i][j]);
                    canvasMatrix[esc][i][j] = new Canvas(bitmapMatrix[esc][i][j]);
                    canvasMatrix[esc][i][j].drawBitmap(bm, 0, 0, paint);
                    if (!text.isEmpty()) {
                        paintText.setColor(Color.rgb(73, 73, 73));
                        if (text.contains("Tejado")) {
                            canvasMatrix[esc][i][j].drawText(text, xOffsetText, yOffsetText * 2, paintText);
                            canvasMatrix[esc][i][j].drawText("NR", xOffsetText, yOffsetText * 3, paintText);
                            if (dataManager.getEscaleras()>1){
                                text = "Escalera ";
                                if (esc==0){
                                    text = text.concat("A");
                                } else {
                                    text = text.concat("B");
                                }
                                canvasMatrix[esc][i][j].drawText(text, xOffsetText, yOffsetText * 4, paintText);
                            }
                        } else {
                            canvasMatrix[esc][i][j].drawText(text, xOffsetText, yOffsetText, paintText);
                            canvasMatrix[esc][i][j].drawText("NR", xOffsetText, yOffsetText * 2, paintText);
                        }
                    } else {
                        canvasMatrix[esc][i][j].drawText("NR", xOffsetText, yOffsetText * 2, paintText);
                    }
                    imageViewMatrix[esc][i][j].invalidate();
                }
            }
        }
    }

    private void drawPeopleInApartment(int planta, int puerta, int esc){
        Bitmap person;
        int cant;

        reDrawApartment(planta,puerta, esc);
        for (int i = 0; i<dataManager.confInApartment(planta,puerta, esc); i++) {
            cant = dataManager.readConfQuant(planta, puerta, i, esc);
            if (cant > 0) {
                if (i == 1) {
                    person = BitmapFactory.decodeResource(this.getResources(), R.drawable.personz4card);
                    paintText.setColor(Color.rgb(206, 137, 26));
                } else if (i == 2) {
                    person = BitmapFactory.decodeResource(this.getResources(), R.drawable.personz5card);
                    paintText.setColor(Color.rgb(138, 16, 16));
                } else if (i == 3) {
                    person = BitmapFactory.decodeResource(this.getResources(), R.drawable.personz6card);
                    paintText.setColor(Color.rgb(73, 73, 73));
                } else {
                    person = BitmapFactory.decodeResource(this.getResources(), R.drawable.personokcard);
                    paintText.setColor(Color.rgb(24, 109, 18));
                }
                canvasMatrix[esc-1][planta][puerta].drawBitmap(person, xOffsetPerson + (i * xOffsetPersonToPerson), yOffsetPerson, paint);
                if (cant > 1){
                    canvasMatrix[esc-1][planta][puerta].drawText(Integer.toString(cant), xOffsetPerson + 5 + (i * xOffsetPersonToPerson), yOffsetPerson + 50, paintText);
                }
            }
        }

        int personQ[] = new int[4];
        personQ[0] = 0;
        personQ[1] = 0;
        personQ[2] = 0;
        personQ[3] = 0;
        int cantE, cantH;
        for (int i=0;i<dataManager.evacInApartment(planta,puerta, esc);i++) {
            cantE = dataManager.readEvacQuant(planta, puerta, i, esc);
            cantH = dataManager.readHospQuant(planta, puerta, i, esc);
            if (i==1) {
                personQ[1] += cantE;
                personQ[1] += cantH;
                paintText.setColor(Color.rgb(206,137,26));
            } else if (i==2) {
                personQ[2] += cantE;
                personQ[2] += cantH;
                paintText.setColor(Color.rgb(138,16,16));
            } else if (i==3) {
                personQ[3] += cantE;
                personQ[3] += cantH;
                paintText.setColor(Color.rgb(73,73,73));
            } else {
                personQ[0] += cantE;
                personQ[0] += cantH;
                paintText.setColor(Color.rgb(24,109,18));
            }
        }

        int offsetTimes = 0;
        for (int i=0;i<personQ.length;i++){
            if (personQ[i]>0) {
                if (i==0){
                    person = BitmapFactory.decodeResource(this.getResources(), R.drawable.personokcardmini);
                    paintText.setColor(Color.rgb(24,109,18));
                } else if (i==1){
                    person = BitmapFactory.decodeResource(this.getResources(), R.drawable.personz4cardmini);
                    paintText.setColor(Color.rgb(206,137,26));
                } else if (i==2){
                    person = BitmapFactory.decodeResource(this.getResources(), R.drawable.personz5cardmini);
                    paintText.setColor(Color.rgb(138,16,16));
                } else {
                    person = BitmapFactory.decodeResource(this.getResources(), R.drawable.personz6cardmini);
                    paintText.setColor(Color.rgb(73,73,73));
                }
                canvasMatrix[esc-1][planta][puerta].drawBitmap(person, xOffsetMini + (offsetTimes * xOffsetMiniToPerson), yOffsetMini, paint);
                canvasMatrix[esc-1][planta][puerta].drawText(Integer.toString(personQ[i]), xOffsetMini - 30 + (offsetTimes * xOffsetMiniToPerson), yOffsetMini + 90, paintText);
                offsetTimes++;
            }
        }

        imageViewMatrix[esc-1][planta][puerta].invalidate();
    }

    private void reDrawApartment(int planta, int puerta, int esc) {
        Bitmap blank;
        String im = dataManager.readImage(planta, puerta, esc);
        String text = dataManager.readText(planta, puerta, esc);
        String estado = dataManager.readState(planta, puerta, esc);
        Boolean rev = dataManager.readInspected(planta, puerta, esc);
        String revisado;
        if (rev) {
            revisado = "R";
        } else {
            revisado = "NR";
        }
        Paint p = paint;

        if (estado.contains("afectado")){
            im = im.concat("_afectado");
        } else if (estado.contains("origen")){
            im = im.concat("_origen");
        }
        if (estado.contains("estructural")){
            im = im.concat("_estructural");
        }

        int id = this.getResources().getIdentifier(im, "drawable", this.getPackageName());
        Bitmap bm = BitmapFactory.decodeResource(this.getResources(), id);
        blank = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), Bitmap.Config.ARGB_8888);
        if (estado.contains("no_existe")){
            im = "no_existe";
            id = this.getResources().getIdentifier(im, "drawable", this.getPackageName());
            bm = BitmapFactory.decodeResource(this.getResources(), id);
        }
        canvasMatrix[esc-1][planta][puerta].drawBitmap(blank,0,0, p);
        if (menuMode) {
            Paint paint3 = new Paint();
            ColorFilter filter = new LightingColorFilter(Color.rgb(185,208,249), 1);
            paint3.setColorFilter(filter);
            if (estado.contains("humo")){
                ColorFilter filter2 = new LightingColorFilter(Color.LTGRAY, 1);
                paint3.setColorFilter(filter2);
            }
            canvasMatrix[esc-1][planta][puerta].drawBitmap(bm,0,0, paint3);
        } else {
            if (estado.contains("humo")){
                p = new Paint();
                ColorFilter filter = new LightingColorFilter(Color.LTGRAY, 1);
                p.setColorFilter(filter);
            }
            canvasMatrix[esc-1][planta][puerta].drawBitmap(bm,0,0, p);
        }
        if (!text.isEmpty()) {
            paintText.setColor(Color.rgb(73, 73, 73));
            if (text.contains("Tejado")) {
                canvasMatrix[esc - 1][planta][puerta].drawText(text, xOffsetText, yOffsetText * 2, paintText);
                canvasMatrix[esc - 1][planta][puerta].drawText(revisado, xOffsetText, yOffsetText * 3, paintText);
                if (dataManager.getEscaleras() > 1) {
                    text = "Escalera ";
                    if (esc == 1) {
                        text = text.concat("A");
                    } else {
                        text = text.concat("B");
                    }
                    canvasMatrix[esc - 1][planta][puerta].drawText(text, xOffsetText, yOffsetText * 4, paintText);
                }
            } else {
                canvasMatrix[esc - 1][planta][puerta].drawText(text, xOffsetText, yOffsetText, paintText);
                canvasMatrix[esc - 1][planta][puerta].drawText(revisado, xOffsetText, yOffsetText * 2, paintText);
            }
        } else {
            canvasMatrix[esc - 1][planta][puerta].drawText(revisado, xOffsetText, yOffsetText * 2, paintText);
        }
    }

    private void setOffsets(){
        Bitmap bm = BitmapFactory.decodeResource(thisActivity.getResources(),R.drawable.personokcard);
        int width = bm.getWidth();
        int height = bm.getHeight();

        xOffsetText = width/3;
        yOffsetText = height/2;

        xOffsetPerson = width/7;
        yOffsetPerson = (int)(height*1.1);
        xOffsetPersonToPerson = (int)(width*1.05);

        xOffsetMini = (int)(width*1.65);
        yOffsetMini = height/4;
        xOffsetMiniToPerson = (int)(width*0.75);
    }


    private void reDrawEvac(){
        ImageView evacView = findViewById(R.id.evacView);
        Bitmap evac = BitmapFactory.decodeResource(this.getResources(), R.drawable.evacuados);
        int w = evac.getWidth();
        int h = evac.getHeight();
        Bitmap bm = Bitmap.createBitmap(w,h,Bitmap.Config.ARGB_8888);
        evacView.setImageBitmap(bm);
        Canvas canv = new Canvas(bm);
        Bitmap pers = BitmapFactory.decodeResource(this.getResources(), R.drawable.person);
        canv.drawBitmap(evac, 0 , 0, paint);
        canv.drawBitmap(pers, xOffsetPerson*10 , yOffsetMini, paint);
        Paint p = new Paint();
        p.setTextSize(180);
        canv.drawText(String.valueOf(dataManager.getEvacuados()),xOffsetText,yOffsetText*2,p);
        evacView.invalidate();
    }

    private void reDrawHosp(){
        ImageView hospView = findViewById(R.id.hospView);
        Bitmap hosp = BitmapFactory.decodeResource(this.getResources(), R.drawable.hospital);
        int w = hosp.getWidth();
        int h = hosp.getHeight();
        Bitmap bm = Bitmap.createBitmap(w,h,Bitmap.Config.ARGB_8888);
        hospView.setImageBitmap(bm);
        Canvas canv = new Canvas(bm);
        Bitmap pers = BitmapFactory.decodeResource(this.getResources(), R.drawable.person);
        canv.drawBitmap(hosp, 0 , 0, paint);
        canv.drawBitmap(pers, xOffsetPerson*10 , yOffsetMini, paint);
        Paint p = new Paint();
        p.setTextSize(180);
        canv.drawText(String.valueOf(dataManager.getHospitalizados()),xOffsetText,yOffsetText*2,p);
        hospView.invalidate();
    }

    private int[] findElementInMatrix(ImageView element){
        boolean found = false;
        int[] coords = new int[2];
        int i;
        int j;
        int esc = 0;
        while (!found && esc<dataManager.getEscaleras()) {
            i = 0;
            while (!found && i < alturaTotal) {
                j = 0;
                while (!found && j < longitudTotal) {
                    if (imageViewMatrix[esc][i][j].equals(element)) {
                        coords[0] = i;
                        coords[1] = j;
                        found = true;
                        escalera = esc+1;
                    }
                    j++;
                }
                i++;
            }
            esc++;
        }
        return coords;
    }

    private void addHospitalText(){
        hospital = "";
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(thisActivity);
        alertDialog.setTitle("HOSPITAL");
        final EditText hosp = new EditText(thisActivity);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT);
        hosp.setLayoutParams(lp);
        alertDialog.setView(hosp);

        alertDialog.setPositiveButton("Guardar", new DialogInterface.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            public void onClick(DialogInterface dialog, int which) {
                hospital = hosp.getText().toString();
                dataManager.addHospPerson(dragCoords[0], dragCoords[1], escalera, hospital);
                reDrawHosp();
                drawPeopleInApartment(dragCoords[0],dragCoords[1], escalera);

            }
        });
        alertDialog.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            public void onClick(DialogInterface dialog, int which) {
                dataManager.addConfPerson(dragCoords[0], dragCoords[1], escalera);
                drawPeopleInApartment(dragCoords[0],dragCoords[1], escalera);
                dialog.cancel();
            }
        });
        alertDialog.show();
    }


    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());
        }
    }

    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];
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void reloadAddress(){
        dataManager = new DataManager(direcciones.get(direccionIndex));
        LinearLayout vertLinearLayout = findViewById(R.id.verticalLayout);
        vertLinearLayout.removeAllViews();
        drawNewBuilding();
        drawAllPeople();
        reDrawEvac();
        reDrawHosp();
        ((TextView)findViewById(R.id.addressText)).setText(direcciones.get(direccionIndex));
        SeekBar seekBar = findViewById(R.id.zoomSeekBar);
        seekBar.setProgress(5);
    }
}