ComprasMainBoard.java 70.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072
package com.focasoftware.deboinventario;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;

public class ComprasMainBoard extends Activity implements DialogPersoSimple,
		Wifi {
	@NonNull
    private Context ctxt = this;
	private CheckBox CheckBorrar;
	private boolean borrar;
	private BaseDatos bdd;
	@NonNull
    BaseDatos bd = new BaseDatos(ctxt);
	private TableLayout tablaPrincipal;
	private ImageView botonSalir;
	private ProgressDialog popupCarga, popupEspera;

	private Button busquedaProveedoresNombre;
	private EditText nomProveedor;
	@NonNull
    GestorLogEventos log = new GestorLogEventos();

	private DialogPersoComplexBusqueda dialogoBusqueda;
	@Nullable
    private EditText edittextBusqueda = null;
	//private HashMap<Integer, Integer> proveedor_resultado_busqueda = null;
	private DialogProveComplexResultados dialogoResultados;

	private ListView list;

	View.OnClickListener listenerBuscarPro;
	/*** Botones para importar y exportar los inventarios*/
	private Button botonExportar, botonImportar, Exportar_BD, Importar_BD, boton_nuevo_inv;
	private RadioButton CheckedInventariosVentas;
	private RadioButton CheckedInventariosDeposito;
	// Parametro para mostrar inventarios de deposito, ventas o compras -3
	private int condR = 0;
/*** Dialogo de aviso para borrar inventarios comunes, se muestra cuando presionamos de forma prolongada un boton de un inventario com�n*/
	private DialogPersoComplexSiNo dialogoBorrarInventario;
	private DialogPersoComplexSiNoInvComp dialogoNuevoInventario;
	/*** Para manejo especial de inventario dinamico*/
	boolean hayDinamicos = false;

	@Nullable
    HashMap<String, String> hashmapInventarioCompra;
	/*** Dialogo que se muestra para preguntar si desea seguir trabajando con el
	 * inventario dinamico actual o empezar de cero*/
	private DialogPersoComplexSiNo dialogoContinuarInventario;
	/*** Dialogo para confirmar la decisi�n de borrar el inventario din�mico
	 * actual y crear uno nuevo desde cero*/
	private DialogPersoComplexSiNo dialogoBorrarInventarioDinamico;
	/*** Lista para almacenar cuales son los inventarios seleccionados con los que se trabajara */
	@NonNull
    private ArrayList<Integer> listaInventariosSeleccionados = new ArrayList<Integer>();
	/**
	 * Dialog donde se informa que se han realizado todas las mediciones para
	 * que proceda a exportar
	 */
	private AlertDialog.Builder dialogoFin;
	private Button elegirProveedor;
	private ArrayList<Proveedor> listaProveedorCompleta;
	@Nullable
    private HashMap<Integer, Integer> proveedor_resultado_busqueda = null;
	private TextView nombreProveedorV;
	private int numero_proveedor;

	private boolean fueCanceladoDialogoResultados = false;

	private int respuestaSeleccionada = -99;
	private int indice_on_focus = -1;
	private int inventarios_elegidos = 0;
	/*** Variable para saber si hay que borrar despues de exportar*/
	boolean borrarDespues = false;
	/*** Dialogos para mostrar opciones de importacion y exportacion para elegir los medios*/
	private DialogPersoComplexExportCompra dialogoPrincipioExport,dialogoPrincipioImport;
	/** Variables de control para saber que tipo de unidad se tiene conectada tanto para esta clase como para la UsbProvider*/
	@NonNull
    public String unidad_final_import = "Dispositivo";
	@NonNull
    public String unidad_final_export = "Dispositivo";
	// se lanza al principio de la clase, para que quede confirurado para la clase usbProvider
	// se verifica el inicio de la ruta configurada sea la correcta /udisk/, /flash/,/sdcard/
	@NonNull
    public String TipoDispositivoImport() {
		// se retorna el resultado y se seteea para que este disponible en cualquier momento
		ParametrosInventario.Dispositivo_Import = unidad_final_import;
		return unidad_final_import;
	}
	// idem anterior
	@NonNull
    public String TipoDispositivoExport() {
		ParametrosInventario.Dispositivo_Export = unidad_final_export;
		return unidad_final_export;
	}

	@NonNull
    private String Dispositivo_Import = TipoDispositivoImport();
	@NonNull
    private String Dispositivo_Export = TipoDispositivoExport();

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.xml_mainboard_compras);
		// Recuperamos tabla:
		tablaPrincipal = (TableLayout) findViewById(R.id.IMB_tabla);
		// Recuperamos los botones:
		botonExportar = (Button) findViewById(R.id.IMB_boton_exportar);
		botonSalir = (ImageView) findViewById(R.id.IMB_boton_salir);
	//	botonImportar = (Button) findViewById(R.id.IMB_boton_importar);
		boton_nuevo_inv = (Button) findViewById(R.id.ADD_boton_nuevo_invc);
		Exportar_BD = (Button) findViewById(R.id.Exportar_BD);
		Importar_BD = (Button) findViewById(R.id.Importar_BD);
		CheckedInventariosVentas = (RadioButton) findViewById(R.id.CheckInventariosVentas);
		CheckedInventariosDeposito = (RadioButton) findViewById(R.id.CheckInventariosDepositos);

		elegirProveedor = (Button) findViewById(R.id.id_proveedor_buscar);
		//nombreProveedorV = (TextView) findViewById(R.id.nombreProveedor);

		Exportar_BD.setOnLongClickListener(new View.OnLongClickListener() {

			public boolean onLongClick(View v) {
				log.log("Se presiono el boton Exportar BD", 3);
				String titulo = "EXPORTACION DE BASE DE DATOS";
				String mensaje = "Se exporto la base de datos";
				showSimpleDialogOK(titulo, mensaje).show();
				try {
					File sourceFile = new File(
							ParametrosInventario.URL_CARPETA_DATABASES
									+ "DB_INVENT");
					File destFile = new File(
							ParametrosInventario.CARPETA_LOGDATOS
									+ "DB_INVENT.sqlite");
					copyFile(sourceFile, destFile);
					Log.e("mensaje, sourceFile", sourceFile.toString());
					Log.e("mensaje, destFile", destFile.toString());
				} catch (Exception e) {
					log.log(e.toString(), 4);
					showSimpleDialogOK(
							"EXPORTACION DE BASE DE DATOS",
							"Se interrumpio, intentelo nuevamente.\n"
									+ "Si el error persiste, reporte el archivo log a Servicio Tecnico")
							.show();
				}

				log.log("Exportacion Realizada con exito", 3);
				return false;
			}

		});
		// Apagamos el Wifi:
		//desactivarWifi();
		// 2� REFRESH DE LA PAGINA PRINCIPAL:
		try {
			refreshTablaPrincipal();
		} catch (ExceptionBDD e1) {
			log.log("[-- 260 --]" + e1.toString(), 2);
			e1.printStackTrace();
			Toast.makeText(ctxt, e1.toString(), Toast.LENGTH_LONG).show();
		} catch (Exception e1) {
			log.log("[-- 265 --]" + e1.toString(), 4);
			e1.printStackTrace();
			Toast.makeText(ctxt, e1.toString(), Toast.LENGTH_LONG).show();
		}

		botonExportar.setOnLongClickListener(new View.OnLongClickListener() {
			public boolean onLongClick(View v) {
				log.log("[-- 276 --]" + "Presiono Exportar", 0);
				BaseDatos bdd = new BaseDatos(ctxt);
				int numero_inventarios_cerrados = 0;
				ArrayList<Integer> inventarios_a_exportar ;
				try {
					inventarios_a_exportar = bdd
							.selectInventariosCerradosEnBddCompras();
					//inventarios_a_exportar = bdd
					//		.selectInventariosNumerosEnBddCompras();
					numero_inventarios_cerrados = inventarios_a_exportar.size();
					if(numero_inventarios_cerrados>=1) {
						inventarios_elegidos = inventarios_a_exportar.get(0);
					}
				} catch (ExceptionBDD e) {
					log.log("[-- 285 --]" + e.toString(), 4);
					log.log("[-- 286 --]" + "Error, la exportacion se cancelo",
							3);
					e.printStackTrace();
					Toast.makeText(ctxt, "Error, la exportacion se cancelo",
							Toast.LENGTH_LONG).show();
					return false;
				}
				if (numero_inventarios_cerrados <= 0) {
					log.log("[-- 297 --]"
									+ "Ningun inventario cerrado, la exportacion se cancelo",3);
					Toast.makeText(
							ctxt,
							"Ningun inventario cerrado, la exportacion se cancelo",
							Toast.LENGTH_LONG).show();
					return false;
				}else if(numero_inventarios_cerrados>=2){
					log.log("[-- 297 --]"
									+ "Debe seleccionar un solo inventario, la exportacion se cancelo",3);
					Toast.makeText(
							ctxt,
							"No puede realizarse la exportacion, solamente debe haber un inventario cerrado para exportar.",
							Toast.LENGTH_LONG).show();
					return false;
				}

				lanzarMenuEspera();

				View.OnClickListener listenerWifi = new View.OnClickListener() {

					public void onClick(View v) {

						log.log("[-- 311 --]" + "Se presiono el boton Wifi ", 0);
						borrarDespues = dialogoPrincipioExport.isBorrar_luego();

						dialogoPrincipioExport.dismiss();

						Intent intentWifi = new Intent(
								ComprasMainBoard.this, WiFiControlador.class);
						startActivityForResult(intentWifi,
								Parametros.REQUEST_WIFI_EXPORT);
					}
				};

				View.OnClickListener listenerUsb = new View.OnClickListener() {

					public void onClick(View v) {

						log.log("[-- 327 --]" + "Se presiono el boton USB ", 0);
						// dialogoPrincipioExport.cancel();
						// dialogoPrincipioExport.hide();
						dialogoPrincipioExport.dismiss();
						int contador = 3;
						try {
							do {
								export_usb(dialogoPrincipioExport.isBorrar_luego());
								contador--;
							} while (control_buena_exportacion() == false
									&& contador >= 0);
						} catch (ExceptionBDD e) {
							showSimpleDialogOK(
									"Error",
									"Generacion del documento XML imposible: "
											+ e.getComentario()).show();
							cerrarMenuEspera();
							return;
						} catch (Exception e) {
							showSimpleDialogOK(
									"Error",
									"Imposible exportar en el "
											+ Dispositivo_Export
											+ ". Verifique que este correcamente "
											+ "conectado").show();
							cerrarMenuEspera();
							return;
						}

						// Si hubo vencimiento del contador:
						if ((control_buena_exportacion() == false)
								|| contador < 0) {
							// Entra aca, por que?
							showSimpleDialogOK(
									"ERROR DE EXPORTACION",
									"Los archivos XML de exportacion del "
											+ Dispositivo_Export
											+ ", no han podido ser creados con exito.")
									.show();
							return;
						}

						cerrarMenuEspera();
					}
				};

				View.OnClickListener listenerNegativo = new View.OnClickListener() {

					public void onClick(View v) {
						dialogoPrincipioExport.cancel();
						cerrarMenuEspera();
					}
				};
					dialogoPrincipioExport = new DialogPersoComplexExportCompra(
							ctxt,
							"MEDIO DE EXPORTACION",
							"Usted esta a punto de exportar los datos de COMPRAS.\n"
									+ "La opcion de  AJUSTAR PRODUCTOS NO INCLUIDOS puede demorar varios minutos.\n\n"
									+ "Al finalizar la Compra sera borrada.",
							true, listenerWifi, listenerNegativo);
					dialogoPrincipioExport.show();
				return true;
			}
		});

		boton_nuevo_inv.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
/******************************************************************************************
*******************************************************************************************/
				//dialogoNuevoInventario
				// 1.1.1 En caso positivo pasa al inventario actual
				View.OnClickListener listenerPositivo = new View.OnClickListener() {
					public void onClick(View v) {
//						log.log("[-- --]"
//								+ "Presiono para ir a los inventarios dinamicos", 0);
						BaseDatos bdd = new BaseDatos(ctxt);
						// Lo que hace con el boton del si
						dialogoNuevoInventario.dismiss();
						// Creamos los inventarios dinamicos
						Inventario inventarioDinamicoCompra = new Inventario(
								ParametrosInventario.ID_INV_COMPRAS,
								"Inv. Comp ",
										//+ String.valueOf(ParametrosInventario.ID_INV_COMPRAS)
										//+ "Compras",
								new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
										.format(new Date()),
								"",
								ParametrosInventario.INVENTARIO_ABIERTO,
								ParametrosInventario.COD_LUGAR_INVENTARIO_VENTA);
						try {

							if(bdd.verificaBaseNueva()==true){
								bdd.verComprasExistentes(inventarioDinamicoCompra);
								Toast.makeText(
										ctxt,
										"Se creo un nuevo inventario de compras.",
										Toast.LENGTH_LONG).show();
								Intent intentInventario = new Intent(ctxt,
										ComprasMainBoard.class);
								startActivityForResult(intentInventario,
										ParametrosInventario.REQUEST_INVENTARIO_COMPRAS);
							}else{
								Toast.makeText(
										ctxt,
										"Debe crear el primero antes de agregar más Inv..",
										Toast.LENGTH_LONG).show();
							}
						} catch (ExceptionBDD exceptionBDD) {
							exceptionBDD.printStackTrace();
						}
					}
				};
				// 1.1.2 En caso negativo muestra otro cartel para verificar si
				// borra
				View.OnClickListener listenerNegativo = new View.OnClickListener() {
					public void onClick(View v) {
						// Lo que hace con el no Debe preguntar nuevamente para eliminar el inventario
						// guardado Abrir otra ventana y preguntar si realmente quiere eliminar los datos
						dialogoNuevoInventario.dismiss();
						// 1.1.2.1 En caso de que quiera borrar se elimina y genera uno nuevo pasando a la Pagina correspondiente
						/*View.OnClickListener listenerPositivo = new View.OnClickListener() {
							public void onClick(View v) {
								log.log("[-- 1617 --]" + "Se presiono el boton si",
										0);
								BaseDatos bdd = new BaseDatos(ctxt);
								// Lo que hace con el boton del si
								dialogoBorrarInventarioDinamico.dismiss();
								// Creamos los inventarios dinamicos
								Inventario inventarioDinamicoCompra = new Inventario(
										ParametrosInventario.ID_INV_COMPRAS,
										"Inv. dinamico "
												+ String.valueOf(ParametrosInventario.ID_INV_COMPRAS)
												+ " de compra",
										new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
												.format(new Date()),
										"",
										ParametrosInventario.INVENTARIO_ABIERTO,
										ParametrosInventario.COD_LUGAR_INVENTARIO_VENTA);
								try {
									// Borrar datos del inventario
									bdd.borrarInventarioConArticulos(ParametrosInventario.ID_INV_COMPRAS);
									// Crearlo de nuevo
									bdd.insertInventarioComprasEnBdd(inventarioDinamicoCompra);
									Toast.makeText(
											ctxt,
											"Se crearon los inventarios dinamicos nuevos",
											Toast.LENGTH_LONG).show();
								} catch (ExceptionBDD e) {
									log.log("[-- 1660 --]" + e.toString(), 4);
									// TODO Auto-generated catch block
									e.printStackTrace();
									Toast.makeText(
											ctxt,
											"Problema al borrar los inventarios de la BD"
													+ e.getMessage(),
											Toast.LENGTH_LONG).show();
								}
								Intent intentInventario = new Intent(ctxt,
										PaginaCompras.class);
								intentInventario
										.putExtra(
												ParametrosInventario.extra_numeroInventarioCompra,
												ParametrosInventario.ID_INV_COMPRAS);
								startActivityForResult(
										intentInventario,
										ParametrosInventario.REQUEST_INVENTARIO_COMPRAS);
							}
						};*/
						// 1.1.2.2 En caso de que no quiera borrar, se vuelve a la
						// pantalla principal
					}
				};
				// 1.1 Genera un dialog que pregunta si se continua con el
				// inventario o se
				// borra y genera algo nuevo
				dialogoNuevoInventario = new DialogPersoComplexSiNoInvComp(
						ctxt,
						"Agregar Inventario Compras",
						"Desea agregar un inventario de compras?",
						DialogPerso.VALIDAR, listenerPositivo, listenerNegativo);

				dialogoNuevoInventario.show();


				/******************************************************************************************
				 * ***************************************************************************************
				 */
				log.log("[-- 396 --]" + "Se presiono Agregar Inv C", 0);
				//	try {
				bdd = new BaseDatos(ctxt);
				//	} catch (ExceptionBDD e) {
				//		log.log("[-- 409 --]" + e.toString(), 4);
				//	}
			}
		});

		botonSalir.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				Intent intentDebo = new Intent(ctxt,
						DeboInventario.class);
				startActivity(intentDebo);
			/*	try {
					if (indice_on_focus >= 0) {
						TableRow linea = (TableRow) tabla_articulos
								.getChildAt(indice_on_focus);
						EditText edittext = (EditText) linea.getChildAt(3);
						InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
						mgr.hideSoftInputFromWindow(edittext.getWindowToken(),
								0);

						deseleccionarLineaParticular(indice_on_focus);
					}
				} catch (Exception e) {
				log.log("[-- 2461 --]" + e.toString(), 4);
					e.printStackTrace();
				} finally {
					setResult(RESULT_OK, intentPadre);
					finish();
				}*/
			}
		});
	/*	botonSalir.setOnTouchListener(new View.OnTouchListener() {

			public boolean onTouch(View v, MotionEvent event) {
				log.log("[-- 473 --]" + "Se presiono salir", 0);
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					ImageView imageV = (ImageView) v;
					imageV.setBackgroundColor(getResources().getColor(
							R.color.orange));
				} else if (event.getAction() == MotionEvent.ACTION_UP) {
					ImageView imageV = (ImageView) v;
					imageV.setBackgroundColor(Color.TRANSPARENT);

					finish();
				}
				return true;
			}
		});*/

	}
	public void elegir(View view, int id_inventario) {
		String convertir_id = String.valueOf(id_inventario);
		Intent i = new Intent(ComprasMainBoard.this, ProveedorBusqueda.class);
		i.putExtra("proveedor", convertir_id);
		startActivity(i);
	}

	private void export_usb(boolean borrar_despues) throws ExceptionBDD,
			Exception {
		// Para prueba descomentar la linea siguiente para que encuentre los archivos ParametrosInventario.PREF_USB_EXPORT =
		// "data/data/com.foca.deboInventario/test/"; 1 Vaciar la carpeta de exportacion
		vaciarCarpetaExportacion();
		bdd = new BaseDatos(ctxt);
		String texto_error = "";
		boolean estado_exportacion = true;
		Dispositivo_Export = TipoDispositivoExport();
		Dispositivo_Export = TipoDispositivoImport();

		// 2 Fabricamos la lista de todos los inventarios que estn cerrados:
		ArrayList<Integer> listaInventariosCerrados = bdd
				.selectInventariosCerradosEnBddCompras();
		if (listaInventariosCerrados.size() <= 0) {
			log.log("[-- 2433 --]"
					+ "Debe haber por lo menos un inventario cerrado", 3);
			Toast.makeText(ctxt,
					"Debe haber por lo menos un inventario cerrado",
					Toast.LENGTH_LONG).show();
			return;
		}

		/**
		 * 3 Llama al proceso de exportacion de las BD al pendrive, esto genera
		 * un archivo o varios XML de export en la carpeta
		 * data/data/com.foca.deboInventario/usb/export
		 */
		if (ParametrosInventario.ProductosNoContabilizados == 2) {
			ArrayList<Referencia> Referencias = new ArrayList<Referencia>();
			BaseDatos bd = new BaseDatos(ctxt);
			Referencias = bd.getArticulosAll();
			for (Referencia ref : Referencias) {
				try {
					Articulo articulo = bd.selectArticuloConCodigos(
							ref.getSector(), ref.getArticulo(), -1);

					if (articulo == null) {
						ArrayList<String> codbar = new ArrayList<String>();
						ArrayList<String> codbarcompleto = new ArrayList<String>();
						codbar.add(ref.getCodigo_barra());
						codbarcompleto.add(ref.getCodigo_barra_completo());
						Articulo art = new Articulo(ref.getSector(),
								ref.getArticulo(),
								ref.getBalanza(),
								ref.getDecimales(),
								codbar,
								codbarcompleto, -1,
								ref.getDescripcion(),
								ref.getPrecio_venta(),
								ref.getPrecio_costo(), "", 0,0,
								ref.getExis_venta(),
								ref.getExis_deposito(),
								ref.getDepsn(),
								"");
						bd.insertArticuloEnBdd(art);
					} else {
						//	Log.e("Referencias con articulos", "No agregar "
						//				+ articulo.getDescripcion().toString());
					}

				} catch (ExceptionBDD e) {
					Toast.makeText(ctxt,
							"Error al recorrer las referencias",
							Toast.LENGTH_LONG).show();
				}
			}
		}

		bdd.exportarTodasBaseDatosSQLite_HaciaUsb(listaInventariosCerrados);

		/**
		 * 4 Copiamos al pen drive todos los archivos XML presentes en la
		 * carpeta de EXPORT, al pendrive y verifica el proceso
		 */

		File carpeta_fuente = new File(
				ParametrosInventario.URL_CARPETA_USB_EXPORT);
		for (File archivo : carpeta_fuente.listFiles()) {
			File carpeta_destino = new File(
					ParametrosInventario.CARPETA_ATABLET);
			File archivo_destino = new File(
					ParametrosInventario.CARPETA_DESDETABLET
							+ archivo.getName());
			// boolean existecarpetaDest=carpeta_destino.exists();
			// boolean existearchivo=archivo.exists();
			try {
				if (carpeta_destino.exists() == true
						&& archivo.exists() == true) {
					// Puede arrojar la IOExc
					archivo_destino.createNewFile();
					// Puede arrojar la IOExc
					copyFile(archivo, archivo_destino);
					archivo.delete();
				} else {
					texto_error = "Imposible encontrar la carpeta de destino: "
							+ carpeta_destino.getPath();
					estado_exportacion = false;
					// Deberiamos crear la carpeta de destino y hacer todo lo
					// anterior
					// carpeta_destino.mkdirs();
					// archivo_destino.createNewFile();
					// copyFile(archivo, archivo_destino);
					archivo.delete();
				}
			} catch (IOException e) {
				// Genera este error
				texto_error = "Un error occurio al momento de copiar los archivos al"
						+ Dispositivo_Export;
				estado_exportacion = false;
			}

			// Control directo sobre el archivo generado:
			if (carpeta_destino.exists() == false) {
				estado_exportacion = false;
			}
		}

		// 5 Se verifica la correcta exportacion, si es positiva se borran los
		// inventarios
		if (estado_exportacion == true && control_buena_exportacion() == true) {
			// Los borramos si nos han marcado o si son dinamicos
			for (int num_inv : listaInventariosCerrados) {
				if (borrar_despues == true || num_inv < 0) {

					bdd.borrarInventarioConArticulos(num_inv);
				}
			}

			showSimpleDialogOK(
					"Exportacion exitosa",
					"Datos correctamente exportados en el "
							+ Dispositivo_Export).show();
		}// Solucion temporaria 08/05/2012
		// else if ()
		else {
			// Se saca para que no moleste despues
			// showSimpleDialogOK("Error", texto_error +
			// "\n Es posible que los archivos de exportacin hayan sido mal generados.\n\n"
			// +
			// "Por favor reintente.").show();
			// Borrar los archivos de la carpeta desdeTablet
			// File carpeta_destino = new
			// File(ParametrosInventario.PREF_USB_EXPORT);
			// for(File archivoDest:carpeta_destino.listFiles()) {
			// archivoDest.delete();
			// }
		}

		cerrarMenuEspera();
		refreshTablaPrincipal();
	}
	/*** Funcin accesoria para vaciar la carpeta de exportacion del pendrive*/
	private void vaciarCarpetaExportacion() {
		File carpeta_destino = new File(
				ParametrosInventario.CARPETA_DESDETABLET);
		for (File archivo : carpeta_destino.listFiles()) {
			// No funciona esto con archivos de menos de 1 byte por lo menos en el emulador
			archivo.delete();
		}
	}
	/**
	 * Lanza un progres dialog de espera
	 */
	private void lanzarMenuEspera() {
		popupEspera = new ProgressDialog(ctxt);
		popupEspera.setCancelable(false);
		popupEspera.setMessage("Exportando los datos...");
		popupEspera.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		popupEspera.show();
	}

	/*** Muestra un dialog de OK*/
	public AlertDialog showSimpleDialogOK(String titulo, String mensaje) {
		log.log("[-- 2215 --]" + "titulo: " + titulo + ", \n mensaje: "
				+ mensaje, 3);
		AlertDialog.Builder dialogoSimple = new AlertDialog.Builder(this);
		dialogoSimple.setCancelable(false).setTitle(titulo).setMessage(mensaje)
				.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
					public void onClick(@NonNull DialogInterface dialog, int id) {
						dialog.dismiss();
					}
				});
		AlertDialog alert = dialogoSimple.create();
		return alert;
	}
	//@Override
	//public AlertDialog showSimpleDialogSiNo(String titulo, String mensaje, Class<?> clase) {
	//	return null;
	//}

	public AlertDialog showSimpleDialogSiNo(String titulo, String mensaje,
                                            @Nullable final Class<?> clase) {
		log.log("[-- 2233 --]" + "titulo: " + titulo + ", \n mensaje: "
				+ mensaje, 3);
		AlertDialog.Builder dialogoSimple = new AlertDialog.Builder(this);
		dialogoSimple
				.setCancelable(false)
				.setTitle(titulo)
				.setMessage(mensaje)
				.setPositiveButton("Si", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						bdd = new BaseDatos(ctxt);

						log.log("[-- 2243 --]" + "Acepto sino", 2);

						// Si CLASE = null, es un EXPORT
						if (clase == null) {
							int contador = 3;

							try {
								do {
									export_usb(false);
									contador--;
								} while (control_buena_exportacion() == false
										&& contador >= 0);
							} catch (ExceptionBDD e) {

								log.log("[-- 2257 --]" + e.toString(), 4);
								showSimpleDialogOK(
										"ERROR DE EXPORTACION",
										"Generacion del documento XML imposible: "
												+ e.getComentario()).show();
								return;
							} catch (Exception e) {
								log.log("[-- 2264 --]" + e.toString(), 4);
								showSimpleDialogOK(
										"ERROR DE EXPORTACION",
										"Imposible exportar en el "
												+ Dispositivo_Export
												+ ". Verifique que este "
												+ "correctamente conectado")
										.show();
								return;
							}

							if (contador < 0) {
								showSimpleDialogOK(
										"ERROR DE EXPORTACION",
										"Los archivos XML de exportacion no han podido ser creados con exito. "
												+ "Verifique su correctitud")
										.show();
								return;
							}

							cerrarMenuEspera();

						}
						// Si CLASE es not NULL, es import:
						else {
							Intent intentUSB = new Intent(
									ComprasMainBoard.this, UsbProvider.class);
							intentUSB.putExtra(Parametros.extra_uri_usb,
									Parametros.PREF_USB_IMPORT);
							startActivity(intentUSB);
							finish();
						}
					}
				})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {
					public void onClick(@NonNull DialogInterface dialog, int id) {
						dialog.cancel();
						log.log("[-- 2301 --]" + "Cancelo sino", 2);
					}
				});
		AlertDialog alert = dialogoSimple.create();
		return alert;
	}

	/**
	 * Funcion accesoria para copiar un archivo de origen en uno de destino
	 * @param sourceFile
	 * @param destFile
	 * @throws IOException
	 */
	private void copyFile(@NonNull File sourceFile, @NonNull File destFile) throws IOException {
		if (!sourceFile.exists()) {
			return;
		}
		if (!destFile.exists()) {
			destFile.createNewFile();
		}
		FileChannel source = null;
		FileChannel destination = null;
		source = new FileInputStream(sourceFile).getChannel();
		destination = new FileOutputStream(destFile).getChannel();
		if (destination != null && source != null) {
			destination.transferFrom(source, 0, source.size());
		}
		if (source != null) {
			source.close();
		}
		if (destination != null) {
			destination.close();
		}
	}

	private void refreshTablaPrincipal() throws ExceptionBDD, Exception {
		HashMap<Integer, HashMap<String, String>> matrizInventarios = new HashMap<Integer, HashMap<String, String>>();
		HashMap<Integer, HashMap<String, String>> matrizInventariosDinamicos = new HashMap<Integer, HashMap<String, String>>();
		tablaPrincipal.removeAllViews();
		control_integridad_tablas();
		BaseDatos bdd = new BaseDatos(ctxt);
		bdd = new BaseDatos(ctxt);
		try {
			matrizInventarios = bdd.selectInventariosCompraEnBdd();
		} catch (ExceptionBDD e2) {
			log.log("[-- 882 --]" + e2.toString() + " NO HAY INVENTARIOS", 4);
			e2.printStackTrace();
		}
		// 4 Configuracin de los botones:
		if (matrizInventarios.size() <= 0) {
			botonExportar.setEnabled(false);
			//botonImportar.setEnabled(true);
			boton_nuevo_inv.setEnabled(true);

			// return;
		} else if (matrizInventarios.size() >= ParametrosInventario.PREF_MAX_COMPRA_ABIERTAS) {
			botonExportar.setEnabled(true);
			//botonImportar.setEnabled(false);
			boton_nuevo_inv.setEnabled(false);
		} else {
			botonExportar.setEnabled(true);
			//botonImportar.setEnabled(true);
			boton_nuevo_inv.setEnabled(true);
		}
		// 5 Si tenemos elementos, construccin de todos los botones de inventarios comunes de la pagina:
		ArrayList<Integer> lista_claves = new ArrayList<Integer>();
		for (int i : matrizInventarios.keySet()) {
			lista_claves.add(i);
		}


		Collections.sort(lista_claves);
		Iterator<Integer> iterator_inventarios_id = lista_claves.iterator();
		while (iterator_inventarios_id.hasNext() == true) {
			// Recupermos los datos:
			final int id_inventario = iterator_inventarios_id.next();
			if (id_inventario < -3) {
				final HashMap<String, String> hashmapUnInventario = matrizInventarios
						.get(id_inventario);
				// Consulta de la completud del inventario:
				ArrayList<Integer> listaEstadisticas = bdd
						.selectEstadisticasConIdInventario(id_inventario);
				int cantidadArticulosEnInventario = listaEstadisticas.get(0);
				int articulosYaContadosEnInventario = listaEstadisticas.get(1);
				// CREACIN DE LA LINEA:
				LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
				TableRow nuevaLinea = (TableRow) inflater.inflate(
						R.layout.z_lineaprogressbar_mainboard_compras, null);
				nuevaLinea
						.setId(ParametrosInventario.ID_LINEAS + id_inventario);
				// Elemento 1 = boton:
				Button b = (Button) nuevaLinea.findViewById(R.id.LPB2_boton);
				//if (id_inventario >= 0) {
				//	b.setText("Inventario " + String.valueOf(id_inventario));
				b.setText("Inventario Compras");
			//	} else {
			//		b.setText("Inv. dinamico "
			//				+ String.valueOf(Math.abs(id_inventario)));
			//	}
				b.setId(ParametrosInventario.ID_BOTONES + id_inventario);
				// Elemento 2 = texto del NOMBRE:
				TextView textoNombre = (TextView) nuevaLinea
						.findViewById(R.id.LPB2_nombre);
				textoNombre.setText(hashmapUnInventario.get(
						ParametrosInventario.bal_bdd_inventario_descripcion)
						.trim());
				// Elemento 3 = texto de la FECHA de CREACION:
				TextView textoFecha = (TextView) nuevaLinea
						.findViewById(R.id.LPB2_inicio);
				textoFecha.setText(hashmapUnInventario.get(
						ParametrosInventario.bal_bdd_inventario_fechaInicio)
						.trim());
				// Elemento 4 = PROGRESS-BAR:
				TextView tv_progressbar = (TextView) nuevaLinea
						.findViewById(R.id.LPB2_texto_progressbar);
				String texto_estadisticas_progresion = String
						.valueOf(articulosYaContadosEnInventario)
						+ " de "
						+ String.valueOf(cantidadArticulosEnInventario);
				tv_progressbar.setText(texto_estadisticas_progresion);
				try {
					ProgressBar pb = (ProgressBar) nuevaLinea
							.findViewById(R.id.LPB2_progressbar);
					int newValue = 0;
					if (cantidadArticulosEnInventario != 0) {
						newValue = (int) Math
								.floor((double) articulosYaContadosEnInventario
										/ (double) cantidadArticulosEnInventario
										* (double) 100);
					}
					pb.setProgress(newValue);
				} catch (Exception e) {
					e.printStackTrace();
				}
				// Elemento 5 = CANDADO:
				ImageView candado = (ImageView) nuevaLinea
						.findViewById(R.id.LPB2_estado);
				if (Integer.parseInt(hashmapUnInventario
						.get(ParametrosInventario.bal_bdd_inventario_estado)) == 1) {
					candado.setImageDrawable(getResources().getDrawable(
							R.drawable.candado_ab));
				} else {
					candado.setImageDrawable(getResources().getDrawable(
							R.drawable.candado_cer));
				}
				System.out.println("::: 700 COMPRAS MAIN BOAR VER SI LLEGA ACCCCCCCCCCCCCCCAAAAAAAA");
				// Elemento 6 = nombre del Proveedor:
				//TextView textoNombreProve = (TextView) nuevaLinea
				//		.findViewById(R.id.id_proveedor_buscar);
				//textoNombreProve.setText("NOMBRE");
				//nombreProveedorV.setText("NOMBRE");

				String cod_prov_string = bdd.proveedorAsignado(id_inventario);
				// Elemento 6 = nombre del Proveedor:
				//Asi estaba con el        android:onClick="elegir"
			//	TextView textoNombreProve = (TextView) nuevaLinea
			//			.findViewById(R.id.id_proveedor_buscar);
			//	textoNombreProve.setText(cod_prov_string);


				Button textoNombreProve = (Button) nuevaLinea.findViewById(R.id.id_proveedor_buscar);
				textoNombreProve .setText(cod_prov_string);
				textoNombreProve .setId(ParametrosInventario.ID_BOTONES + id_inventario);
/*
 * ****************************************
						 * ********************************/
				textoNombreProve.setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {
						log.log("[-- 994 --]" + "Presion un inventario ", 0);
						elegir(v,id_inventario);
						System.out.println("::: SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII V");
					}
				});
/****************************************************************************************/

				// Creacin del handler:
				b.setOnClickListener(new View.OnClickListener() {
					public void onClick(@NonNull View v) {
						log.log("[-- 994 --]" + "Presion un inventario ", 0);
						BaseDatos bdd = new BaseDatos(ctxt);
						System.out.println("::: 1 ComprasMainBoard CUAL ABREEEE " + v.getId());
						try {
							if (bdd.estaAbiertoInventarioComprasConId(v.getId()
									- ParametrosInventario.ID_BOTONES) == true) {
								ClicBoton((Button) v);
							} else {
								log.log("[-- 1002 --]"
										+ "Inventario cerrado con candado", 3);
								Toast.makeText(ctxt,
										"Inventario cerrado con candado",
										Toast.LENGTH_LONG).show();
							}
						} catch (ExceptionBDD e) {
							log.log("[-- 1009 --]" + e.toString(), 4);
							e.printStackTrace();
							Toast.makeText(ctxt,
									"Inventario cerrado con candado",
									Toast.LENGTH_LONG).show();
						}
					}
				});
				b.setOnLongClickListener(new View.OnLongClickListener() {

					public boolean onLongClick(@NonNull View v) {
						log.log("[-- 1043 --]"
										+ "Se hizo un clic largo sobre un ionventario",
								0);
						try {
							final int id_invent_con_boton = v.getId()
									- ParametrosInventario.ID_BOTONES;
							BaseDatos bdd = new BaseDatos(ctxt);
							System.out.println("::: 2 ComprasMainBoard CUAL ABREEEE " + v.getId());
							if (bdd.estaAbiertoInventarioComprasConId(id_invent_con_boton) == true) {
								View.OnClickListener listenerPositivo = new View.OnClickListener() {

									public void onClick(View v) {
										log.log("[-- --]"
														+ "Se presion el boton para borrar el inventario",
												0);
										// Aqui borramos el inventario:
										BaseDatos bdd = new BaseDatos(ctxt);
										try {
											bdd.borrarInventarioConArticulos(id_invent_con_boton);
										} catch (ExceptionBDD e) {

											log.log("[-- 1065 --]"
													+ e.toString(), 4);
											e.printStackTrace();
										}
										try {
											refreshTablaPrincipal();
										} catch (ExceptionBDD e) {
											log.log("[-- 1073 --]"
													+ e.toString(), 4);
											e.printStackTrace();
										} catch (Exception e) {
											log.log("[-- 1077 --]"
													+ e.toString(), 4);
											e.printStackTrace();
										}
										dialogoBorrarInventario.dismiss();
									}
								};
								View.OnClickListener listenerNegativo = new View.OnClickListener() {

									public void onClick(View v) {
										log.log("[-- --]"
												+ "Se presiono cancelar", 0);
										dialogoBorrarInventario.cancel();
									}
								};
								dialogoBorrarInventario = new DialogPersoComplexSiNo(
										ctxt,
										"SUPRIMIR INVENTARIO",
										"Usted esta a punto de suprimir el inventario n"
												+ String.valueOf(id_invent_con_boton)
												+ "\n\n"
												+ "Esta seguro de querer suprimir este inventario?",
										DialogPerso.ALERTAR, listenerPositivo,
										listenerNegativo);
								dialogoBorrarInventario.show();
							} else {
								Toast.makeText(
										ctxt,
										"Supresion imposible: inventario cerrado con candado",
										Toast.LENGTH_LONG).show();
							}
						} catch (ExceptionBDD e) {
							log.log("[-- 1114 --]" + e.toString(), 4);
							e.printStackTrace();
							Toast.makeText(ctxt,
									"Inventario cerrado con candado",
									Toast.LENGTH_LONG).show();
							log.log("[-- 1120 --]"
									+ "Inventario cerrado con candado", 3);
						}
						return true;
					}

				});
				// Creacin de los handlers:
				candado.setOnClickListener(new View.OnClickListener() {

					public void onClick(View v) {
						log.log("[-- 1133 --]" + "Se presiono el candado", 0);
						try {
						//	System.out.println("::: -------!!!!!!!________!!!!!!--------");
							ImageView iv = (ImageView) v;
							BaseDatos bdd = new BaseDatos(ctxt);
							if (Integer.parseInt(hashmapUnInventario
									.get(ParametrosInventario.bal_bdd_inventario_estado)) == ParametrosInventario.INVENTARIO_ABIERTO) {
								bdd.updateInventario(
										Integer.parseInt(hashmapUnInventario
												.get(ParametrosInventario.bal_bdd_inventario_numero)),
										ParametrosInventario.INVENTARIO_CERRADO);
								hashmapUnInventario
										.put(ParametrosInventario.bal_bdd_inventario_estado,
												String.valueOf(ParametrosInventario.INVENTARIO_CERRADO));
								iv.setImageDrawable(getResources().getDrawable(
										R.drawable.candado_cer));
							} else {
								bdd.updateInventario(
										Integer.parseInt(hashmapUnInventario
												.get(ParametrosInventario.bal_bdd_inventario_numero)),
										ParametrosInventario.INVENTARIO_ABIERTO);
								hashmapUnInventario
										.put(ParametrosInventario.bal_bdd_inventario_estado,
												String.valueOf(ParametrosInventario.INVENTARIO_ABIERTO));
								iv.setImageDrawable(getResources().getDrawable(
										R.drawable.candado_ab));
							}
						} catch (Exception e) {
							log.log("[-- 1164 --]" + e.toString(), 4);
							e.printStackTrace();
						} catch (ExceptionBDD e) {
							log.log("[-- 1168 --]" + e.toString(), 4);
							e.printStackTrace();
						}
					}
				});
			/*ESTO Impide que YO vea los otros inventarios*/
				/*
				elegirProveedor.setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {
					System.out.println("::: ESTO CREO Q GENERA EL ERROR");
					}
				});
*/

				// AGREGAMOS LA LINEA A LA TABLA:
				tablaPrincipal.addView(nuevaLinea);

			} else {
				// Meter los dinamicos en un arreglo
				matrizInventariosDinamicos.put(id_inventario,
						matrizInventarios.get(id_inventario));
			}

		} // end while

		/**
		 * Trabajo que se hace para los inventarios dinmicos similar a los
		 * otros pero con un tratamiento especial por que es un boton que esta
		 * siempre y fijo y tiene una funcionalidad definida
		 */
		// 6 Creacion de estructuras y la linea del inventario dinmico

		// Verificamos que no hayan inventarios dinamicos para crear una linea
		// vacia
		if (matrizInventariosDinamicos.size() == 0) {
			hayDinamicos = false;
		} else {
			// Caso en el que hay inventarios dinamicos de antes
			hayDinamicos = true;
		}

		hashmapInventarioCompra = matrizInventariosDinamicos
				.get(ParametrosInventario.ID_INV_COMPRAS);

		int id_inv_ficticio = -3;

		ArrayList<Integer> listaEstadisticas = new ArrayList<Integer>();
		int articulosTotalesQueInventariar = 0, articulosNonInventariados = 0;

		int cantidadArticulosEnInventario = 0, articulosYaContadosEnInventario = 0;
		// Si es ficticio es 0
		if (hayDinamicos) {
			ArrayList<Integer> listaEstadisticasCompra;
			// Buscar info en la base de datos y completar las variables
			listaEstadisticasCompra = bdd
						.selectEstadisticasConIdInventario(ParametrosInventario.ID_INV_COMPRAS);
				cantidadArticulosEnInventario = listaEstadisticasCompra.get(0);
				articulosYaContadosEnInventario = listaEstadisticasCompra.get(1);
		} else {
			listaEstadisticas.add(articulosTotalesQueInventariar);
			listaEstadisticas.add(articulosTotalesQueInventariar
					- articulosNonInventariados);
			listaEstadisticas.add(articulosNonInventariados);
			cantidadArticulosEnInventario = listaEstadisticas.get(0);
			articulosYaContadosEnInventario = listaEstadisticas.get(1);
		}
		// CREACIN DE LA LINEA:
		LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
		TableRow nuevaLinea = (TableRow) inflater.inflate(
				R.layout.z_lineaprogressbar_mainboard_compras, null);
		nuevaLinea.setId(ParametrosInventario.ID_LINEAS + id_inv_ficticio);
		// nuevaLinea.setId(ParametrosInventario.ID_LINEA_DINAMICO);
		System.out.println("::: INVDIN 1347 Creacion de la linea id_inv_ficticio " + id_inv_ficticio);
		// Elemento 1 = boton:
		Button b = (Button) nuevaLinea.findViewById(R.id.LPB2_boton);
		b.setText("Inventario Compras");
		b.setId(ParametrosInventario.ID_BOTONES + id_inv_ficticio);
		// Elemento 2 = texto del NOMBRE:
		TextView textoNombre = (TextView) nuevaLinea
				.findViewById(R.id.LPB2_nombre);
		textoNombre.setText("Inv. Comp");
		// Elemento 3 = texto de la FECHA de CREACION:
		TextView textoFecha = (TextView) nuevaLinea
				.findViewById(R.id.LPB2_inicio);
		if (hayDinamicos) {
			String fecha="";
				condR=-3;
				String fechaIVta = hashmapInventarioCompra.get(
						ParametrosInventario.bal_bdd_inventario_fechaInicio).trim();
				fecha = hashmapInventarioCompra.get(
						ParametrosInventario.bal_bdd_inventario_fechaInicio)
						.trim();
			textoFecha.setText(fecha);
		} else {
			textoFecha.setText("");
		}
		// Elemento 4 = PROGRESS-BAR:
		TextView tv_progressbar = (TextView) nuevaLinea
				.findViewById(R.id.LPB2_texto_progressbar);
		String texto_estadisticas_progresion = String
				.valueOf(articulosYaContadosEnInventario)
				+ " de "
				+ String.valueOf(cantidadArticulosEnInventario);
		tv_progressbar.setText(texto_estadisticas_progresion);
		try {
			ProgressBar pb = (ProgressBar) nuevaLinea
					.findViewById(R.id.LPB2_progressbar);
			int newValue = 0;
			if (cantidadArticulosEnInventario != 0) {
				newValue = (int) Math
						.floor((double) articulosYaContadosEnInventario
								/ (double) cantidadArticulosEnInventario
								* (double) 100);
			}
			pb.setProgress(newValue);
		} catch (Exception e) {
			log.log("[-- 1326 --]" + e.toString(), 4);
			e.printStackTrace();
		}
		// Elemento 5 = CANDADO:
		ImageView candado = (ImageView) nuevaLinea
				.findViewById(R.id.LPB2_estado);
		System.out.println("::: 700 2 COMPRAS MAIN BOAR VER SI LLEGA ACCCCCCCCCCCCCCCAAAAAAAA");


		String cod_prov_string = bdd.proveedorAsignado(-3);
		// Elemento 6 = nombre del Proveedor:
		//Asi estaba con el        android:onClick="elegir"
//		TextView textoNombreProve = (TextView) nuevaLinea
//				.findViewById(R.id.id_proveedor_buscar);
//		textoNombreProve.setText(cod_prov_string);

		Button textoNombreProve = (Button) nuevaLinea.findViewById(R.id.id_proveedor_buscar);
		textoNombreProve .setText(cod_prov_string);
		textoNombreProve .setId(ParametrosInventario.ID_BOTONES + -3);
/****************
 * ****************************************
 * ********************************/
		textoNombreProve.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				log.log("[-- 994 --]" + "Presion un inventario ", 0);
				elegir(v , -3);
				System.out.println("::: SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII V");
			}
		});
/********************************************************
 * ********************************/


		if (hayDinamicos) {
			// Se verifica que esten los dos cerrados
			int estadoCandadoCom = 0;
			estadoCandadoCom = Integer.parseInt(hashmapInventarioCompra
						.get(ParametrosInventario.bal_bdd_inventario_estado));
				if (estadoCandadoCom == 1){
					candado.setImageDrawable(getResources().getDrawable(
							R.drawable.candado_ab));
				} else {
					candado.setImageDrawable(getResources().getDrawable(
							R.drawable.candado_cer));
				}
		} else {
			// Se dibuja abierto
			candado.setImageDrawable(getResources().getDrawable(
					R.drawable.candado_ab));
		}
		// Creacin del handler del boton:
		b.setOnClickListener(new View.OnClickListener() {
			public void onClick(@NonNull View v) {
				BaseDatos bdd = new BaseDatos(ctxt);
				System.out.println("::: 3 ComprasMainBoard CUAL ABREEEE " + v.getId());
				if (hayDinamicos) {
					try {
							if (bdd.estaAbiertoInventarioConId(v.getId()
									- ParametrosInventario.ID_BOTONES) == true) {
								ClicBotonDinamico((Button) v);
								//ClicBoton((Button) v);
							} else {
								log.log("[-- --]"
										+ "Inventario cerrado con candado", 3);
								Toast.makeText(ctxt,
										"Inventario cerrado con candado",
										Toast.LENGTH_LONG).show();
							}
					} catch (ExceptionBDD e) {
						log.log("[-- 1372 --]" + e.toString(), 3);
						e.printStackTrace();
						Toast.makeText(ctxt, "Inventario cerrado con candado",
								Toast.LENGTH_LONG).show();
					}
				} else {
					ClicBotonDinamico((Button) v);
					//ClicBoton((Button) v);
				}
			}
		});

		// Creacin de los handlers:
		candado.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				try {
					ImageView iv = (ImageView) v;
					int estadoCandadoCom = 0;
					BaseDatos bdd = new BaseDatos(ctxt);
					if (hayDinamicos) {
						// Se verifica que esten los dos cerrados
						//if(condR == -1){
						estadoCandadoCom = Integer.parseInt(hashmapInventarioCompra
								.get(ParametrosInventario.bal_bdd_inventario_estado));
					} else {
					}
					if (estadoCandadoCom == ParametrosInventario.INVENTARIO_ABIERTO) {
						// Actualizamos, cerrando el inventario dinamico de
						// venta
						bdd.updateInventario(
								ParametrosInventario.ID_INV_COMPRAS,
								ParametrosInventario.INVENTARIO_CERRADO);
						hashmapInventarioCompra
								.put(ParametrosInventario.bal_bdd_inventario_estado,
										String.valueOf(ParametrosInventario.INVENTARIO_CERRADO));
						iv.setImageDrawable(getResources().getDrawable(
								R.drawable.candado_cer));
					} else {
						// Los guardo como abiertos
						bdd.updateInventario(
								ParametrosInventario.ID_INV_COMPRAS,
								ParametrosInventario.INVENTARIO_ABIERTO);
						hashmapInventarioCompra
								.put(ParametrosInventario.bal_bdd_inventario_estado,
										String.valueOf(ParametrosInventario.INVENTARIO_ABIERTO));
						iv.setImageDrawable(getResources().getDrawable(
								R.drawable.candado_ab));
					}

				} catch (Exception e) {
					log.log("[-- 1449 --]" + e.toString(), 4);
					e.printStackTrace();
				} catch (ExceptionBDD e) {
					log.log("[-- 1454 --]" + e.toString(), 4);
					e.printStackTrace();
				}
			}
		});
		// AGREGAMOS LA LINEA A LA TABLA:
		tablaPrincipal.addView(nuevaLinea);
	// desactivarWifi();
	}// Fin de la funcin
	/*** Verifica que los inventarios tengan articulos*/
	private void control_integridad_tablas() {
		try {
			BaseDatos bdd = new BaseDatos(ctxt);
				condR=-3;
		ArrayList<Integer> lista_numeros_inventarios = bdd
					.selectInventariosNumerosEnBddCompras();
			if (lista_numeros_inventarios != null) {
				for (int id_inv : lista_numeros_inventarios) {
					if (id_inv >= 0
							&& bdd.selectArticulosCodigosConNumeroInventario(
							id_inv).size() <= 0) {
						bdd.borrarInventarioConArticulos(id_inv);
					}
				}
			}
		} catch (ExceptionBDD e) {
			e.printStackTrace();
			log.log("[-- 2594 --]" + e.toString(), 4);
		}
	}

	/**
	 * Metodo que manejea el funcionamiento de los botones de la tabla al
	 * hacerles click en el caso comun, entra a la activity
	 * PaginaInventario.java, pasando como parmetro el valor del numero de
	 * inventario asociado al boton
	 *
	 * @param boton
	 */
	private void ClicBoton(@NonNull Button boton) {
		int numeroInventarioAsociadoAlBoton = (boton.getId() - ParametrosInventario.ID_BOTONES);
		Intent intentInventario = new Intent(ctxt, PaginaCompras.class);
		intentInventario.putExtra(ParametrosInventario.extra_numeroInventarioCompra,
				numeroInventarioAsociadoAlBoton);
		// intentInventario.putExtra(ParametrosInventario.extra_bandera_invs_dinamicos,
		// ParametrosInventario.extra_valor_bandera_invs_dinamicos_no);
		startActivityForResult(intentInventario,
				ParametrosInventario.REQUEST_INVENTARIO_COMPRAS);
	}

	private void ClicBotonDinamico(Button boton) {
		// 1 Si hay inventarios creados debe preguntar por eliminar o seguir con el anterior
		if (hayDinamicos) {
			// 1.1.1 En caso positivo pasa al inventario actual
			View.OnClickListener listenerPositivo = new View.OnClickListener() {

				public void onClick(View v) {
					// Lo que hace con el boton del si
					log.log("[-- --]"
							+ "Presiono para ir a los inventarios dinamicos", 0);
					dialogoContinuarInventario.dismiss();
					Intent intentInventario = new Intent(ctxt,
							PaginaCompras.class);
					intentInventario.putExtra(
							ParametrosInventario.extra_numeroInventarioCompra,
							ParametrosInventario.ID_INV_COMPRAS);
					 intentInventario.putExtra(ParametrosInventario.extra_bandera_invs_dinamicos,
					 ParametrosInventario.extra_valor_bandera_invs_dinamicos_si);
					startActivityForResult(intentInventario,
							ParametrosInventario.REQUEST_INVENTARIO_COMPRAS);
				}
			};
			// 1.1.2 En caso negativo muestra otro cartel para verificar si
			// borra
			View.OnClickListener listenerNegativo = new View.OnClickListener() {

				public void onClick(View v) {
					// Lo que hace con el no Debe preguntar nuevamente para eliminar el inventario
					// guardado Abrir otra ventana y preguntar si realmente quiere eliminar los datos
					dialogoContinuarInventario.dismiss();
					// 1.1.2.1 En caso de que quiera borrar se elimina y genera uno nuevo pasando a la Pagina correspondiente
					View.OnClickListener listenerPositivo = new View.OnClickListener() {

						public void onClick(View v) {
							log.log("[-- 1617 --]" + "Se presiono el boton si",
									0);
							BaseDatos bdd = new BaseDatos(ctxt);
							// Lo que hace con el boton del si
							dialogoBorrarInventarioDinamico.dismiss();
							// Creamos los inventarios dinamicos
							Inventario inventarioDinamicoCompra = new Inventario(
									ParametrosInventario.ID_INV_COMPRAS,
									"Inv. dinamico "
											+ String.valueOf(ParametrosInventario.ID_INV_COMPRAS)
											+ " de compra",
									new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
											.format(new Date()),
									"",
									ParametrosInventario.INVENTARIO_ABIERTO,
									ParametrosInventario.COD_LUGAR_INVENTARIO_VENTA);
							try {
								// Borrar datos del inventario
								bdd.borrarInventarioConArticulos(ParametrosInventario.ID_INV_COMPRAS);
								// Crearlo de nuevo
								bdd.insertInventarioComprasEnBdd(inventarioDinamicoCompra);
								Toast.makeText(
										ctxt,
										"Se crearon los inventarios dinamicos nuevos",
										Toast.LENGTH_LONG).show();
							} catch (ExceptionBDD e) {
								log.log("[-- 1660 --]" + e.toString(), 4);
								// TODO Auto-generated catch block
								e.printStackTrace();
								Toast.makeText(
										ctxt,
										"Problema al borrar los inventarios de la BD"
												+ e.getMessage(),
										Toast.LENGTH_LONG).show();
							}
							Intent intentInventario = new Intent(ctxt,
									PaginaCompras.class);
							intentInventario
									.putExtra(
											ParametrosInventario.extra_numeroInventarioCompra,
											ParametrosInventario.ID_INV_COMPRAS);
							startActivityForResult(
									intentInventario,
									ParametrosInventario.REQUEST_INVENTARIO_COMPRAS);
						}
					};
					// 1.1.2.2 En caso de que no quiera borrar, se vuelve a la
					// pantalla principal
					View.OnClickListener listenerNegativo = new View.OnClickListener() {

						public void onClick(View v) {
							log.log("[-- 1692 --]" + "Se presiono el boton no",
									0);
							// Lo que hace con el no
							// Debe preguntar nuevamente para eliminar el
							// inventario guardado
							// Abrir otra ventana y preguntar si realmente
							// quiere eliminar los datos
							dialogoBorrarInventarioDinamico.dismiss();
						}
					};
					dialogoBorrarInventarioDinamico = new DialogPersoComplexSiNo(
							ctxt,
							"Nueva Compra",
							"Si genera una nueva compra se borrara cualquier " +
									"compra en curso que se estuviera realizando aun no exportada.\nCUIDADO:"
									+ "Los datos no han sido exportados al sistema DEBO BackOffice para ser "
									+ "procesados para el correcto control de stock y se borraran",
							DialogPerso.ALERTAR, listenerPositivo,
							listenerNegativo);
					dialogoBorrarInventarioDinamico.show();
				}
			};
			// 1.1 Genera un dialog que pregunta si se continua con el
			// inventario o se
			// borra y genera algo nuevo
			dialogoContinuarInventario = new DialogPersoComplexSiNo(
					ctxt,
					"Continuar Compras",
					"Desea continuar trabajando con la recepcion de compra actual?",
					DialogPerso.VALIDAR, listenerPositivo, listenerNegativo);

			dialogoContinuarInventario.show();

		} else {
			// 2 Si no hay inventarios , Se deben crear 2 inventarios (uno para
			// venta y otro para deposito)
			// Logica de creacion de los inventarios dinamicos, las ponemos aca
			// Proceso de creacin del inventario nuevo:

			bdd = new BaseDatos(ctxt);

			// 2.1 Creo los objetos para los dos inventarios nuevos
			final Inventario inventarioDinamicoCompra = new Inventario(
					ParametrosInventario.ID_INV_COMPRAS,
					"Inv. dinamico "
							+ String.valueOf(ParametrosInventario.ID_INV_COMPRAS)
							+ " de venta", new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss").format(new Date()), "",
					ParametrosInventario.INVENTARIO_ABIERTO,
					ParametrosInventario.COD_LUGAR_INVENTARIO_VENTA);
			// 2.2 Insertamos en la base de datos:
			try {
//				if (ParametrosInventario.InventariosVentas == true) {
				bdd.insertInventarioComprasEnBdd(inventarioDinamicoCompra);
				Toast.makeText(ctxt,
						"Se crearon los inventarios dinamicos nuevos",
						Toast.LENGTH_LONG).show();
				try {
					refreshTablaPrincipal();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} catch (ExceptionBDD e) {
				log.log("[-- 1769 --]" + e.toString(), 4);
				showSimpleDialogOK("Error",
						"La creacion del inventario fue cancelada").show();
			}
			// 2.3 Pasamos a la pantalla de administracion de inventario
			// dinamico
			Intent intentInventario = new Intent(ctxt,
					PaginaCompras.class);
			intentInventario.putExtra(
					ParametrosInventario.extra_numeroInventarioCompra,
					ParametrosInventario.ID_INV_COMPRAS);
			startActivityForResult(intentInventario,
					ParametrosInventario.REQUEST_INVENTARIO_COMPRAS);
		}

	}

	public void onActivityResult(int requestCode, int resultCode,
                                 @Nullable Intent intentRespondido) {
		try {
			super.onActivityResult(requestCode, resultCode, intentRespondido);
			Bundle bundle = null;
			if (intentRespondido != null) {
				bundle = intentRespondido.getExtras();
			}
			// 1 Volvemos de Pagina inventario o Dinmico:refrescamos la tabla
			// y
			// controlamos si hay alguno para cerrar
			if (requestCode == ParametrosInventario.REQUEST_INVENTARIO) {
				try {
					refreshTablaPrincipal();
					controlFin();
				} catch (ExceptionBDD e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else if (requestCode == ParametrosInventario.REQUEST_INVENTARIO_DINAMICO) {
				try {
					refreshTablaPrincipal();

					controlFin();
				} catch (ExceptionBDD e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else if (requestCode == ParametrosInventario.REQUEST_INVENTARIO_COMPRAS) {
				try {
					refreshTablaPrincipal();

					controlFin();
				} catch (ExceptionBDD e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
			/*
			} else if (requestCode == Parametros.REQUEST_WIFI_IMPORT
					&& resultCode == RESULT_OK) {
				// cerrarMenuEspera();
				// 2 Si volvemos de WIFI import todo bien, vamos a seleccionar
				// Inventario
				Intent intentInventario = new Intent(ctxt,
						SeleccionInventarios.class);
				startActivity(intentInventario);
				finish();
			} else if (requestCode == Parametros.REQUEST_WIFI_IMPORT
					&& resultCode != RESULT_OK) {
				// cerrarMenuEspera();
				// 3 Si hubo un error con WIFI import da la opcin de cargar
				// por USB
				desactivarWifi();
				showSimpleDialogSiNo(
						"Error de conexion a la red",
						"La red hasta el servidor no ha podido ser establecida (1).\n\nUsted desea importar sus datos por medio de un Dispositivo (conectelo en aquel caso)?",
						UsbProvider.class).show();
						*/
			} else if (requestCode == Parametros.REQUEST_WIFI_EXPORT
					&& resultCode == RESULT_OK) {
				// 4 Si volvemos de WIFI Export todo OK vamos a hacer
				// exportacion por WIFI
				ExportarDatos unaExportacion = new ExportarDatos();
				unaExportacion.execute(ctxt);

			} else if (requestCode == Parametros.REQUEST_WIFI_EXPORT
					&& resultCode != RESULT_OK) {
				// 5 Si volvemos de WIFI export

				cerrarMenuEspera();
				desactivarWifi();
				dialogoFin = new AlertDialog.Builder(this);
				dialogoFin
						.setTitle("Error de conexion a la red")
						.setMessage(
								"La red hasta el servidor no ha podido ser establecida (2).\n (Intente conectarse nuevamente a la red)")
						.setCancelable(false)
						.setNeutralButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(@NonNull DialogInterface dialog,
                                                        int which) {
										dialog.dismiss();
									}
								});
				AlertDialog alert = dialogoFin.create();
				alert.show();
			}

		} catch (Exception e) {

			log.log("[-- 492 --]" + e.toString(), 4);
			e.printStackTrace();
			showSimpleDialogOK("Error", e.toString()).show();
		}
	}

	private void controlFin() throws ExceptionBDD {
		if (estanTerminadosTodosLosInventarios() == true) {
			botonExportar.setEnabled(true);

			dialogoFin = new AlertDialog.Builder(this);
			dialogoFin
					.setTitle("Fin de las mediciones")
					.setMessage(
							"Todas los inventarios han sido procesados exitosamente.\n"
									+ "Por favor, dirijase hacia el central de control para descargar los datos de los inventarios al servidor.")
					.setCancelable(false)
					.setNeutralButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(@NonNull DialogInterface dialog,
                                                    int which) {
									dialog.dismiss();
								}
							});
			AlertDialog alert = dialogoFin.create();
			alert.show();
		}
	}

	/**
	 * Verifica si estan todos los inventarios terminados en la BD para avisar
	 * que se exporten posteriormente
	 *
	 * @return
	 * @throws ExceptionBDD
	 */
	private boolean estanTerminadosTodosLosInventarios() throws ExceptionBDD {
		boolean result = true;
		BaseDatos bdd = new BaseDatos(ctxt);
		listaInventariosSeleccionados = bdd.selectInventariosNumerosEnBddCompras();
		for (int numInventario : listaInventariosSeleccionados) {
			if (bdd.selectEstadisticasConIdInventario(numInventario).get(2) > 0) {
				result = false;
			}
		}
		return result;
	}
	void mostrarMensaje(int valorRecibido){
			if(valorRecibido == 0){
				Toast.makeText(ctxt,
						"El articulo no tiene habilitado el deposito",
						Toast.LENGTH_LONG).show();
			}
	}

	/**
	 * Tarea asincronica de exportacion de los datos
	 * @author DamianC
	 */
	protected class ExportarDatos extends
			AsyncTask<Context, Integer, RespuestasExportar> {
		private static final boolean Referencia = false;
		@NonNull
        protected RespuestasExportar doInBackground(Context... arg0) {
			boolean result = true;
			if (ParametrosInventario.ProductosNoContabilizados == 2) {
				ArrayList<Referencia> Referencias = new ArrayList<Referencia>();
				BaseDatos bd = new BaseDatos(ctxt);
				String fechaInicioInventario  = "";
				int numero_inventario_elegido = inventarios_elegidos;
				if(inventarios_elegidos==-3 ){
					try {
						Inventario inven = bd.selectInventarioConNumeroCompra(-3);
					} catch (ExceptionBDD e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					System.out.println("::: PASO por InventarioM 4");
					Referencias = bd.getArticulosAll();
					for (Referencia ref : Referencias) {
						try {
							System.out.println("::: PASO por InventarioM 5");
							Articulo articulo = bd.selectArticuloConCodigos(
									ref.getSector(), ref.getArticulo(), -1);
							if (articulo == null) {
								Date fechaHoy = new Date();
								ArrayList<String> codbar = new ArrayList<String>();
								ArrayList<String> codbarcompleto = new ArrayList<String>();
								String fechaYA = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
								Articulo art = new Articulo(ref.getSector(),
										ref.getArticulo(), ref.getBalanza(), ref.getDecimales(), codbar,
										codbarcompleto , -1,
										ref.getDescripcion(),
										ref.getPrecio_venta(),
										ref.getPrecio_costo(), "", 0,
										ref.getExis_venta(),
										ref.getExis_deposito(),
										ref.getDepsn(),
										fechaInicioInventario,fechaYA);
								bd.insertArticuloEnBdd_conFechaFin(art);
							} else {
								System.out.println("::: InventarioMainBoard ");
								Log.e("Referencia con articulo", "No agregar "+ articulo.getDescripcion().toString());
							}
						} catch (ExceptionBDD e) {
							Toast.makeText(ctxt,
									"Error al recorrer las referencias",
									Toast.LENGTH_LONG).show();
							result = false;
						}
					}
				}else if(inventarios_elegidos >0){
				}
			}else{
				try {
					System.out.println("::: 1688 ComprasMainBoard " + inventarios_elegidos);
					//Inventario inven = bd.selectInventarioConNumeroParametro(-3,ParametrosInventario.ProductosNoContabilizados);
					Inventario inven = bd.selectInventarioConNumeroParametro(inventarios_elegidos,ParametrosInventario.ProductosNoContabilizados);
				} catch (ExceptionBDD e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			try {
				RegistroLog.log(ParametrosInventario.URL_ARCHIVO_LOG,
						new Date(), "MAIN BOARD", "0", "Export: 0 %");
			} catch (Exception e) {
				log.log("[-- 1943 --]" + e.toString(), 4);
				e.printStackTrace();
			}
			try {
				bdd = new BaseDatos(ctxt);
				// 1 Fabricamos la lista de todos los inventarios que estn cerrados:
				ArrayList<Integer> listaInventariosCerrados = null;
				try {
					listaInventariosCerrados = bdd
							.selectInventariosCerradosEnBddCompras();
				} catch (ExceptionBDD e4) {
					log.log("[-- 1959 --]" + e4.toString(), 4);
					e4.printStackTrace();
				}
				if (listaInventariosCerrados.size() <= 0) {
					Toast.makeText(ctxt,
							"Debe haber por lo menos un inventario cerrado",
							Toast.LENGTH_LONG).show();
					result = false;
				}
				try {
					// 2 se realiza la exportacin de los datos en las BD
					result = bdd.exportarTodasBaseDatosSQLiteCompras(listaInventariosCerrados);
				} catch (ExceptionHttpExchange e2) {

					log.log("[-- 1961 --]" + e2.toString(), 4);
					e2.printStackTrace();
					return new RespuestasExportar(
							RespuestasExportar.CODIGO_ERROR,
							"Error Export - Export a la BDD - Articulos - "
									+ e2.toString());
				} catch (ExceptionBDD e) {

					log.log("[-- 1969 --]" + e.toString(), 0);
					e.printStackTrace();
					return new RespuestasExportar(
							RespuestasExportar.CODIGO_ERROR,
							"Error Export - Export a la BDD - Articulos - "
									+ e.toString());
				}

				// 3 Exportamos los estados de los inventarios:
				try {
					if (result == true) {
						HttpSender httpSender = new HttpSender(
								Parametros.CODIGO_SOFT_DEBOINVENTARIO);
						for (int inventario : listaInventariosCerrados) {
							if (bdd.selectArticulosConNumeroInventarioCompra(
									inventario).size() <= 0) {
								result &= httpSender.send_liberacion(
										inventario, 0);
							} else {
								result &= httpSender.send_liberacion(
										inventario, 1);
							}

							// 4 A ver si borrar estuvo activado o no,o si es
							// dinamico el inventario:
							if (borrarDespues == true || inventario < 0) {
								bdd.borrarInventarioConArticulos(inventario);
							}
						}
					}
				} catch (ExceptionHttpExchange e2) {

					log.log("[-- 2001 --]" + e2.toString(), 4);
					e2.printStackTrace();
					return new RespuestasExportar(
							RespuestasExportar.CODIGO_ERROR,
							"Error Export - Export a la BDD - Inventarios - "
									+ e2.toString());
				} catch (ExceptionBDD e) {
					log.log("[-- 2022 --]" + e.toString(), 4);

				} catch (Exception e3) {
					log.log("[-- 2024 --]" + e3.toString(), 4);
					e3.printStackTrace();
					return new RespuestasExportar(
							RespuestasExportar.CODIGO_ERROR,
							"Error Export - Export a la BDD - Inventarios - "
									+ e3.toString());
				}

				int i = 1;

				// 5 Comprobamos que todo paso bien
				if (result == false) {
					return new RespuestasExportar(
							RespuestasExportar.CODIGO_ERROR,
							"Error Export - Export a la BDD - Verifique la conexion a la red");
				}

				try {
					RegistroLog.log(ParametrosInventario.URL_ARCHIVO_LOG,
							new Date(), "MAIN BOARD", "0", "Export: 20 %");
				} catch (Exception e) {
					log.log("[-- 2054 --]" + e.toString(), 4);
					e.printStackTrace();
				}

				i = 2;
				// 6 Exportamos las fotos:
				File carpetaFotos = new File(
						ParametrosInventario.URL_CARPETA_FOTOS);
				i = 3;
				if (carpetaFotos.listFiles().length > 0) {
					i = 4;
					HttpSender senderFotos;
					try {
						senderFotos = new HttpSender(
								Parametros.CODIGO_SOFT_DEBOINVENTARIO);
					} catch (ExceptionHttpExchange e) {

						log.log("[-- 2046 --]" + e.toString(), 4);
						e.printStackTrace();
						return new RespuestasExportar(
								RespuestasExportar.CODIGO_WARNING,
								"Error Export - Export imagenes - "
										+ e.toString());
					}

					for (File unaFoto : carpetaFotos.listFiles()) {
						result &= senderFotos
								.send_foto(ParametrosInventario.URL_CARPETA_FOTOS
										+ unaFoto.getName());
					}
				}
				i = 5;
				// 6.1 Comprobar que todo esta bien
				if (result == false) {
					return new RespuestasExportar(
							RespuestasExportar.CODIGO_WARNING,
							"Error Export - Export imagenes");
				}
				i = 6;

				try {
					RegistroLog.log(ParametrosInventario.URL_ARCHIVO_LOG,
							new Date(), "MAIN BOARD", "0", "Export: 40 %");
				} catch (Exception e) {
					e.printStackTrace();

					log.log("[-- 2075 --]" + e.toString(), 4);
				}

				// 7 Exportamos los logs:
				File archivoLOG = new File(ParametrosInventario.URL_ARCHIVO_LOG);
				i = 7;
				if (archivoLOG.exists() == true) {
					HttpSender senderLOG;
					try {
						senderLOG = new HttpSender(
								Parametros.CODIGO_SOFT_DEBOINVENTARIO);
						result = senderLOG
								.send_txt(ParametrosInventario.URL_ARCHIVO_LOG);
					} catch (ExceptionHttpExchange e) {

						e.printStackTrace();
						return new RespuestasExportar(
								RespuestasExportar.CODIGO_WARNING,
								"Error Export - Export logs - " + e.toString());
					}

					i = 8;

					// 7.1 Comprobar que todo esta bien:
					if (result == false) {
						return new RespuestasExportar(
								RespuestasExportar.CODIGO_WARNING,
								"Error Export - Export logs");
					}
					i = 9;
					// archivoLOG.delete();
					i = 10;
				}

				try {
					RegistroLog.log(ParametrosInventario.URL_ARCHIVO_LOG,
							new Date(), "MAIN BOARD", "0", "Export: 60 %");
				} catch (Exception e) {

					log.log("[-- 2114 --]" + e.toString(), 4);
					e.printStackTrace();
				}

				try {
					RegistroLog.log(ParametrosInventario.URL_ARCHIVO_LOG,
							new Date(), "MAIN BOARD", "0", "Export: 90 %");
				} catch (Exception e) {
					log.log("[-- 2136 --]" + e.toString(), 4);
					e.printStackTrace();
				}

			} catch (Exception e) {
				return new RespuestasExportar(RespuestasExportar.CODIGO_ERROR,
						"Error Export - " + " - Error fatal - "
								+ e.toString());
			}

			return new RespuestasExportar(RespuestasExportar.CODIGO_OK,
					"Operacion Realizada con Exito");
		} // end doInBackground

		/**
		 * Tareas de aviso cuando se finalizo la tarea asincronica, segun
		 * resultados
		 */

		protected void onPostExecute(@NonNull RespuestasExportar result) {
			super.onPostExecute(result);

			// Terminamos la exportacion con un mesaje + refresh:
			cerrarMenuEspera();
			desactivarWifi();

			if (result.getCodigoError() == RespuestasExportar.CODIGO_OK) {
				showSimpleDialogOK("Exportacion Exitosa",
						"La exportacion se realizo con exito.").show();

				try {
					RegistroLog.log(ParametrosInventario.URL_ARCHIVO_LOG,
							new Date(), "MAIN BOARD", "0",
							"Export: 100 % --- EXITOSO");
				} catch (Exception e) {
					log.log("[-- 2170 --]" + e.toString(), 4);
					e.printStackTrace();
				}

				try {
					refreshTablaPrincipal();
				} catch (ExceptionBDD e) {
					log.log("[-- 2176 --]" + e.toString(), 4);
					e.printStackTrace();
				} catch (Exception e) {
					log.log("[-- 2178 --]" + e.toString(), 4);
					e.printStackTrace();
				}

				// Registro.log(ParametrosSancion.URL_ARCHIVO_LOG, new Date(),
				// nombreClase, String.valueOf(operadorId),
				// "Exportar datos 100%");
				// finish();
			} else {
				if (result.getCodigoError() == RespuestasExportar.CODIGO_ERROR) {
					showSimpleDialogOK("Exportacion Cancelada",
							"Explicacion: \n\n" + result.getMensaje()).show();
				} else if (result.getCodigoError() == RespuestasExportar.CODIGO_WARNING) {
					showSimpleDialogOK(
							"Exportacion Finalizada con Advertencias",
							"Explicacion: \n\n" + result.getMensaje()).show();
				}
				try {
					RegistroLog.log(ParametrosInventario.URL_ARCHIVO_LOG,
							new Date(), "MAIN BOARD", "0", "Export: 100 % --- "
									+ result);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

	}

	/** Devuelve una informacin sobre el tamao de los archivos (aqui los archivos de exportacin). Si los archivos son de tamaos inferiores a 1
	 * bytes, se considera que el archivo esta vacio.
	 * @return (boolean) TRUE si los archivos tienen un tamao aceptable, FALSE	sino.*/
	private boolean control_buena_exportacion() {
		File carpeta_destino = new File(
				ParametrosInventario.CARPETA_DESDETABLET);
		boolean respuesta = true;
		// Controlamos la integridad de todos los archivos de export
		for (File archivo : carpeta_destino.listFiles()) {
			Long tamaoArchivo = new Long(archivo.length());
			int resultadoComparacion = tamaoArchivo.compareTo(new Long(1L));
			int comparativa = -1;
			boolean esMenor = (resultadoComparacion == comparativa);
			if (esMenor) {
				respuesta = false;
				break;
			}
		}
		return respuesta;
	}

	/**
	 * Cierra el menu de espera
	 */
	private void cerrarMenuEspera() {
		popupEspera.dismiss();
	}

	@Override
	public void activarWifi() {

	}

	@Override
	public void desactivarWifi() {

	}

	@Override
	public boolean estaEnModoAvion() {
		return false;
	}
}