function foto_a_800(item) {
  return new Promise(function(resolve, reject) {
    let lastDot = item.name.lastIndexOf('.');
    let ext = item.name.slice(lastDot + 1);
    
    if (ext === 'pdf') {
      pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.9.359/pdf.worker.min.js';
      var pdfUrl = URL.createObjectURL(item);
      pdfjsLib.getDocument(pdfUrl).promise.then(function(pdf) {
        pdf.getPage(1).then(function(page) {
          var viewport = page.getViewport({ scale: 1.0 });
          var aspectRatio = viewport.width / viewport.height;
          var newWidth = 800;
          var newHeight = newWidth / aspectRatio;
          var canvas = document.createElement('canvas');
          var context = canvas.getContext('2d');
          canvas.width = newWidth;
          canvas.height = newHeight;

          var scale = newWidth / viewport.width;
          var scaledViewport = page.getViewport({ scale: scale });

          page.render({
            canvasContext: context,
            viewport: scaledViewport
          }).promise.then(function() {
            canvas.toBlob(function(blob) {
              resolve(blob);
            }, "image/jpeg");
          });
        });
      });
    } else {
      var resizeWidth = 800;
      var reader = new FileReader();
      reader.onload = function(e) {
        var img = new Image();
        img.onload = function() {
          var aspectRatio = img.width / img.height;
          var newWidth = 800;
          var newHeight = newWidth / aspectRatio;
          var canvas = document.createElement("canvas");
          canvas.width = newWidth;
          canvas.height = newHeight;

          var ctx = canvas.getContext("2d");
          ctx.drawImage(img, 0, 0, newWidth, newHeight);

          canvas.toBlob(function(blob) {
            resolve(blob);
          }, "image/jpeg");
        };
        img.src = e.target.result;
      };
      reader.readAsDataURL(item);
    }
  });
}

function obtengo_fotos(array_fotos) {
  return new Promise((resolve, reject) => {
      if (array_fotos.length === 0) {
          resolve([]); // Resolvemos inmediatamente si no hay fotos
          return;
      }

      const peticiones = array_fotos.map(foto => {
          return fetch(foto).then(response => {
              if (response.ok) {
                  let fecha = response.headers.get('Last-Modified');
                  let fechadate = new Date(fecha);
                  let fechafin = app.obtengo_fecha(fechadate);
                  return { foto: foto, fecha: fechafin };
              } else {
                  throw new Error(`Error fetching ${foto}`); // Manejo de errores si la respuesta no es correcta
              }
          });
      });

      // Esperamos a que todas las peticiones se resuelvan
      Promise.all(peticiones)
          .then(resultado => {
              resolve(resultado); // Devuelve el resultado completo
          })
          .catch(error => {
              reject(error); // Rechaza en caso de error en alguna de las peticiones
          });
  });
}





    function generarImagenDesdePDF(pdfFile, callback) {
      var reader = new FileReader();
      reader.onload = function (e) {
        var pdfData = new Uint8Array(e.target.result);
    
        // Cargar el PDF
        pdfjsLib.getDocument({ data: pdfData }).promise.then(function (pdf) {
          // Obtener la primera página del PDF
          pdf.getPage(1).then(function (page) {
            var scale = 1.5;
            var viewport = page.getViewport({ scale: scale });
    
            // Crear un lienzo en el cual dibujar la imagen
            var canvas = document.createElement("canvas");
            var context = canvas.getContext("2d");
            canvas.width = viewport.width;
            canvas.height = viewport.height;
    
            // Renderizar la página en el lienzo
            var renderContext = {
              canvasContext: context,
              viewport: viewport,
            };
            page.render(renderContext).promise.then(function () {
              // Convertir el lienzo en una imagen JPG
              var imgData = canvas.toDataURL("image/jpeg");
    
              // Llamar al callback con la imagen generada
              callback(imgData);
            });
          });
        });
      };
      reader.readAsArrayBuffer(pdfFile);
    }



    function obtengo_audios(array_audios){
      return new Promise((resolve,reject)=>{
        let resultado = [];
        if (array_audios != [])
          {     
                      for (let i=0;i<array_audios.length;i++){
                        fetch(array_audios[i]).then(function(response) {
                          if(response.ok) {
                            let fecha = response.headers.get('Last-Modified');
                            let fechadate = new Date(fecha);
                            let fechafin = app.obtengo_fecha(fechadate);
                            let elemento = {audio: array_audios[i],fecha: fechafin};
                            resultado.push(elemento);
                            if(i == (array_audios.length - 1))
                            {
                             resolve(resultado);
                            }
                          }
            });
            } 
          }  
            else
            {
              resolve(resultado);
            }
          });
    } 

                      

              function  radian2degree(rad){
                          let pi = 3.14159265358979;	
                                return (rad / pi * 180.0);
                        }
              function  degree2radian(deg){
                          let pi = 3.14159265358979;
                          return (deg/180.0*pi);
                        }
              function  UTMCentralMeridian(zone){
                          let cmeridian = degree2radian(-183.0 + (zone * 6.0));
                          return cmeridian;
                        }
              function  LatLonToUTMXY (lat, lon, zone){
                                let xy = MapLatLonToXY (lat, lon, UTMCentralMeridian(zone));
                                let UTMScaleFactor = 0.9996;
                                xy[0] = xy[0] * UTMScaleFactor + 500000.0;
                                xy[1] = xy[1] * UTMScaleFactor;
                                if (xy[1] < 0.0)
                                    xy[1] = xy[1] + 10000000.0;
                                return xy;
                        }
              function  UTMXYToLatLon (x, y, zone, southhemi){
                                let latlon = [];
                                let UTMScaleFactor = 0.9996;
                                x -= 500000.0;
                                x /= UTMScaleFactor;
                                if (southhemi)
                                  y -= 10000000.0;
                                y /= UTMScaleFactor;
                                let cmeridian = UTMCentralMeridian (zone);
                                latlon = MapXYToLatLon (x, y, cmeridian);	
                                return latlon;
                        }
              function  MapXYToLatLon (x, y, lambda0){
                                let philambda = [];
                                let sm_b = 6356752.314;
                                let sm_a = 6378137.0;
                                let UTMScaleFactor = 0.9996;
                                let sm_EccSquared = 0.00669437999013;
                                let phif = FootpointLatitude (y);
                                let ep2 = (Math.pow (sm_a, 2.0) - Math.pow (sm_b, 2.0)) / Math.pow (sm_b, 2.0);
                                let cf = Math.cos (phif);
                                let nuf2 = ep2 * Math.pow (cf, 2.0);
                                let Nf = Math.pow (sm_a, 2.0) / (sm_b * Math.sqrt (1 + nuf2));
                                let Nfpow = Nf;
                                let tf = Math.tan (phif);
                                let tf2 = tf * tf;
                                let tf4 = tf2 * tf2;
                                let x1frac = 1.0 / (Nfpow * cf);
                                Nfpow *= Nf;   
                                let x2frac = tf / (2.0 * Nfpow);
                                Nfpow *= Nf;   
                                let x3frac = 1.0 / (6.0 * Nfpow * cf);
                                Nfpow *= Nf;   
                                let x4frac = tf / (24.0 * Nfpow);
                                Nfpow *= Nf;   
                                let x5frac = 1.0 / (120.0 * Nfpow * cf);
                                Nfpow *= Nf;   
                                let x6frac = tf / (720.0 * Nfpow);
                                Nfpow *= Nf;   
                                let x7frac = 1.0 / (5040.0 * Nfpow * cf);
                                Nfpow *= Nf;   
                                let x8frac = tf / (40320.0 * Nfpow);
                                let x2poly = -1.0 - nuf2;
                                let x3poly = -1.0 - 2 * tf2 - nuf2;
                                let x4poly = 5.0 + 3.0 * tf2 + 6.0 * nuf2 - 6.0 * tf2 * nuf2- 3.0 * (nuf2 * nuf2) - 9.0 *  tf2 * ( nuf2 *  nuf2);
                                let x5poly = 5.0 + 28.0 * tf2 + 24.0 * tf4 + 6.0 * nuf2 + 8.0 * tf2 * nuf2;
                                let x6poly = -61.0 - 90.0 * tf2 - 45.0 * tf4 - 107.0 * nuf2	+ 162.0 * tf2 * nuf2;
                                let x7poly = -61.0 - 662.0 * tf2 - 1320.0 * tf4 - 720.0 * (tf4 * tf2);
                                let x8poly = 1385.0 + 3633.0 * tf2 + 4095.0 * tf4 + 1575 * (tf4 * tf2);
                                philambda[0] = phif + x2frac * x2poly * (x * x)
                                  + x4frac * x4poly * Math.pow (x, 4.0)
                                  + x6frac * x6poly * Math.pow (x, 6.0)
                                  + x8frac * x8poly * Math.pow (x, 8.0);
                                philambda[1] = lambda0 + x1frac * x
                                  + x3frac * x3poly * Math.pow (x, 3.0)
                                  + x5frac * x5poly * Math.pow (x, 5.0)
                                  + x7frac * x7poly * Math.pow (x, 7.0);                               
                                return philambda;
                        }

              function  FootpointLatitude (y){
                                  let sm_b = 6356752.314;
                                  let sm_a = 6378137.0;
                                  let UTMScaleFactor = 0.9996;
                                  let sm_EccSquared = 0.00669437999013;
                                  let  n = (sm_a - sm_b) / (sm_a + sm_b);
                                  let alpha_ = ((sm_a + sm_b) / 2.0)* (1 +(Math.pow (n, 2.0) / 4) +(Math.pow (n, 4.0) / 64));
                                  let y_ = y / alpha_;
                                  let beta_ = (3.0 * n / 2.0) + (-27.0 * Math.pow (n, 3.0) / 32.0)+ (269.0 * Math.pow (n, 5.0) / 512.0);
                                  let gamma_ = (21.0 * Math.pow (n, 2.0) / 16.0)+ (-55.0 * Math.pow (n, 4.0) / 32.0);
                                  let  delta_ = (151.0 * Math.pow (n, 3.0) / 96.0)+ (-417.0 * Math.pow (n, 5.0) / 128.0);
                                  let epsilon_ = (1097.0 * Math.pow (n, 4.0) / 512.0);
                                  let result = y_ + (beta_ * Math.sin (2.0 * y_))
                                    + (gamma_ * Math.sin (4.0 * y_))
                                    + (delta_ * Math.sin (6.0 * y_))
                                    + (epsilon_ * Math.sin (8.0 * y_));
                                return result;
                        }
              function  MapLatLonToXY (phi, lambda, lambda0){
                          let xy=[];
                          let sm_b = 6356752.314;
                          let sm_a = 6378137.0;
                          let UTMScaleFactor = 0.9996;
                          let sm_EccSquared = 0.00669437999013;
                          let ep2 =(Math.pow (sm_a, 2.0) - Math.pow (sm_b, 2.0)) / Math.pow (sm_b, 2.0);
                          let nu2 = ep2 * Math.pow(Math.cos (phi), 2.0);
                          let N = Math.pow (sm_a, 2.0) / (sm_b * Math.sqrt (1 + nu2));
                          let t = Math.tan (phi);
                          let t2 = t * t;
                          let tmp = (t2 * t2 * t2) - Math.pow (t, 6.0);
                          let l = lambda - lambda0;
                          let l3coef = 1.0 - t2 + nu2;
                          let  l4coef = 5.0 - t2 + 9 * nu2 + 4.0 * (nu2 * nu2);
                          let  l5coef = 5.0 - 18.0 * t2 + (t2 * t2) + 14.0 * nu2- 58.0 * t2 * nu2;
                          let  l6coef = 61.0 - 58.0 * t2 + (t2 * t2) + 270.0 * nu2- 330.0 * t2 * nu2;
                          let l7coef = 61.0 - 479.0 * t2 + 179.0 * (t2 * t2) - (t2 * t2 * t2);
                          let l8coef = 1385.0 - 3111.0 * t2 + 543.0 * (t2 * t2) - (t2 * t2 * t2);
                          xy[0] = N * Math.cos (phi) * l
                                    + (N / 6.0 * Math.pow(Math.cos (phi), 3.0) * l3coef * Math.pow (l, 3.0))
                                    + (N / 120.0 * Math.pow(Math.cos (phi), 5.0) * l5coef * Math.pow (l, 5.0))
                                    + (N / 5040.0 * Math.pow(Math.cos (phi), 7.0) * l7coef * Math.pow (l, 7.0));
                          xy[1] = ArcLengthOfMeridian (phi)
                                    + (t / 2.0 * N * Math.pow(Math.cos (phi), 2.0) * Math.pow (l, 2.0))
                                    + (t / 24.0 * N * Math.pow(Math.cos (phi), 4.0) * l4coef * Math.pow (l, 4.0))
                                    + (t / 720.0 * N * Math.pow(Math.cos (phi), 6.0) * l6coef * Math.pow (l, 6.0))
                                    + (t / 40320.0 * N * Math.pow(Math.cos (phi), 8.0) * l8coef * Math.pow (l, 8.0));
                          return xy;
                        }
            function  ArcLengthOfMeridian(phi){
                                  let sm_b = 6356752.314;
                                  let sm_a = 6378137.0;
                                  let UTMScaleFactor = 0.9996;
                                  let  sm_EccSquared = 0.00669437999013;
                                  let n = (sm_a - sm_b) / (sm_a + sm_b);
                                  let  alpha = ((sm_a + sm_b) / 2.0)
                                                * (1.0 +(Math.pow (n, 2.0) / 4.0) +(Math.pow (n, 4.0) / 64.0));
                                  let  beta = (-3.0 * n / 2.0) + (9.0 * Math.pow (n, 3.0) / 16.0)
                                  + (-3.0 * Math.pow (n, 5.0) / 32.0);
                                  let gamma = (15.0 * Math.pow (n, 2.0) / 16.0)
                                    + (-15.0 * Math.pow (n, 4.0) / 32.0);
                                    let delta = (-35.0 * Math.pow (n, 3.0) / 48.0)
                                    + (105.0 * Math.pow (n, 5.0) / 256.0);
                                    let epsilon = (315.0 * Math.pow (n, 4.0) / 512.0);
                                    let  result = alpha* (phi + (beta * Math.sin (2.0 * phi))
                                    + (gamma * Math.sin (4.0 * phi))
                                    + (delta * Math.sin (6.0 * phi))
                              + (epsilon * Math.sin (8.0 * phi)));
                          return result;
                        }









                        

class dl_coordenadas
{
    static utm2ll(x,y){
                      if(!isNaN(x) || !isNaN(y))
                      {
                        if (x < 167000 || x > 833000 || y > 7000000 || y < 5000000)
                        {
                        return {lat:0,lon:0};
                        }
                      }
                        let latlon = UTMXYToLatLon (x, y, 21, true);
                        return {lat:radian2degree(latlon[0]),lon:radian2degree(latlon[1])};
                      }
    static ll2utm(lat,lon){
                        if(!isNaN(lon) || !isNaN(lat)){
                          if(lon<-59.0 || lon>-51.0 || lat<-36.0 || lat>-29.0){
                          return {lat:0,lon:0};
                          }
                        }
                        let result = LatLonToUTMXY(degree2radian(lat),degree2radian(lon),21);
                        return {x:result[0],y:result[1]};
                      }
}


class dl_geometria {
  static dl_distancia_metros_de_geograficas(lat1,lon1,lat2,lon2)
  {
      let p1 = dl_coordenadas.ll2utm(lat1,lon1);
      let p2 = dl_coordenadas.ll2utm(lat2,lon2);
      let res = Math.sqrt(Math.pow(p2['x'] - p1['x'], 2) + Math.pow(p2['y'] - p1['y'], 2) * 1.0);
      return res;
  }
  static dl_punto_cercano_linestring(lat,lon,linestring)
  { 
      let res = {distancia:9999999,lat:lat,lon:lon};
      let menor_distancia = 99999999;
      let distancia = 0;
      let closestPoint = [];
      let punto_anterior = false;
      let Puntores = false;
      let uuu = -1;
      linestring = linestring.replace(/[A-z()]/g, '');
      let puntos = linestring.split(",");
      for(let i = 0;i<puntos.length;i++)
              {  
                  let punto = puntos[i];
                  let puntoarr = punto.split(' ');
                  puntoarr[0] = parseFloat(puntoarr[0]);
                  puntoarr[1] = parseFloat(puntoarr[1]);
                  if (punto_anterior != false && punto_anterior[1] != puntoarr[1])
                  {
                          let deltax = puntoarr[0] - punto_anterior[0];
                          let deltay = puntoarr[1] - punto_anterior[1];
                          if (deltax != 0 || deltay != 0)
                          {
                          uuu =  ((lon - punto_anterior[0]) * deltax + (lat - punto_anterior[1]) * deltay) / (deltax * deltax + deltay * deltay);
                          }  
                          if (uuu < 0)
                          {
                          closestPoint = {lon:punto_anterior[0],lat:punto_anterior[1]};       
                          }
                          else if (uuu > 1)
                          {
                          closestPoint = {lon:puntoarr[0],lat:puntoarr[1]};       
                          }
                          else
                          {
                          let lonres =  punto_anterior[0] + uuu * deltax;
                          let latres =  punto_anterior[1] + uuu * deltay;
                          closestPoint = {lon:lonres,lat:latres};
                          }
                          distancia = dl_geometria.dl_distancia_metros_de_geograficas(lat,lon,closestPoint['lat'], closestPoint['lon']);
                          if (distancia < menor_distancia)
                          {
                              menor_distancia = distancia;
                              Puntores = closestPoint;
                          } 
                  }
                  punto_anterior = puntoarr;
              }
      if (Puntores != false)
      {        
      distancia = dl_geometria.dl_distancia_metros_de_geograficas(lat,lon,Puntores['lat'],Puntores['lon']);
      if (distancia < 200)
      {
        res = {distancia:distancia,lat:Puntores['lat'],lon:Puntores['lon']};
      }
      }
      return res;
  }
}
