#!/usr/bin/perl

#-------------------------------COMENTARIO GLOBAL---------------
#---------------------------------------------------------------
# PROPOSITO.
#-----------
# Funciones relatos
#---------------------------------------------------------------
# DECLARACIONES GLOBALES.
#------------------------

package lib_mam;
use utf8;
use strict;

sub regeneraVistas {
    my ($artic) = @_;

    my $ts = $artic->{ts};
    my $path_artic = $artic->{fullpath_xml};
    # Carga datos de los relatos
    my %data_rel = &getDatosRelato($ts);
    # my %data_cab = &getDatosCab($ts);
    # my %data_pun = &getDatosPun($ts);

    # Se hace un purge al final, del artículo
    my $fileurl = $artic->get_friendly_url();
    lib_prontus::purge_cache($fileurl);
    print STDERR "Agregando al purge: $fileurl\n";

    my $dir_dest = &getPathMaM($ts, 1) . '/site';
    return 0 if  (!glib_fildir_03::check_dir($dir_dest));
    print STDERR "Chequeando dir_dest[$dir_dest]\n";

    # Parsea todas las plantillas del directorio de cabecera
    my $dir_src = "$prontus_varglb::DIR_SERVER$prontus_varglb::CONFIG{$prontus_varglb::PRONTUS_ID}{'DIR_TEMPLATES'}$prontus_varglb::DIR_MAM";
    print STDERR "dir_src: $dir_src\n";
    my @files = glib_fildir_03::lee_dir($dir_src);

    my %campos_xml = $artic->get_xml_content();
    my $total_rel = scalar keys %data_rel;

    # Path completo al articulo a generar
    my $fullpath_vista = $artic->get_fullpath_artic('', $campos_xml{'_plt'});
    # Se recorren todas las plantillas
    foreach my $file (@files) {
        next if (substr($file, 0, 1) eq '.');
        # Si no es un archivo, no lo parsea
        my $template = $dir_src.'/'.$file;
        next unless(-f $template && -s $template);
        # Se lee la plantilla
        my $buffer = glib_fildir_03::read_file($template);

        # parsear globales de prontus
        $buffer = &lib_prontus::parse_globals($buffer);

        # Parsea loop de lps relatos
        $buffer =~ /%%loop%%(.*?)%%\/loop%%/sg;
        my $loop = $1;
        my $looptotal;
        my $loopcounter = 1;
        my $page = 1;

        foreach my $id_mam (sort {$b <=> $a} keys %data_rel) {
            my $looptemp = $loop;

            # agregamos loop counter
            $data_rel{$id_mam}{'_loopcounter'} = $loopcounter;
            $data_rel{$id_mam}{'_totartics'} = $total_rel;

            # reemplaza marcas del relato
            foreach my $key (keys %{$data_rel{$id_mam}}) {
                next if ($key eq 'mam_txt');
                $looptemp = &lib_prontus::replace_in_artic($data_rel{$id_mam}{$key}, $key, $looptemp);
            }
            # reemplaza vtxt del relato
            $looptemp = $artic->_parsing_vtxt($looptemp, 'mam_txt', $data_rel{$id_mam}{'mam_txt'});

            # Procesar IFs y NIFs
            $looptemp = lib_prontus::procesa_condicional($looptemp, \%campos_xml, $data_rel{$id_mam});

            $looptotal = $looptotal . $looptemp;
            $loopcounter++;
        }

        $buffer =~ s/%%loop%%.*?%%\/loop%%/$looptotal/sg;

        # Procesar IFs y NIFs
        $buffer = &lib_prontus::procesa_condicional($buffer, \%campos_xml);

        # Parsea datos del artic
        $buffer = $artic->parse_artic_data($fullpath_vista, $buffer, \%campos_xml);

        # prontus functions
        $buffer = lib_prontus::parser_custom_function($buffer);

        $buffer =~ s/%%.*?%%//g;

        glib_fildir_03::write_file($dir_dest.'/'.$file, $buffer);
    }
}

# Lee los relatos y devuelve un hash con todos los datos
sub getDatosRelato {
    my ($ts) = @_;
    my %data_rel = ();

    my $mam_dir = &getPathMaM($ts, 1);
    my $indiceRelatosPath = $mam_dir. "/$prontus_varglb::INDEX_MAM";
    my $buffer_index = glib_fildir_03::read_file_bin($indiceRelatosPath);

    my $index_rel = eval { JSON::decode_json($buffer_index) };
    if ($@) {
        print STDERR "Error al decodificar json: $@, path[$indiceRelatosPath] json:[$buffer_index]\n";
    } else {
        foreach my $id (keys %{$index_rel->{'mam'}}) {
            my $path = $mam_dir. "/$id.json";
            my $buffer = glib_fildir_03::read_file_bin($path);
            my $relato = eval { JSON::decode_json($buffer) };
            if ($@) {
                print STDERR "Error al decodificar json: $@, path[$indiceRelatosPath] json:[$buffer_index]\n";
                next;
            }
            $data_rel{$id} = $relato;
        }
    }
    return %data_rel;
}

sub getPathMaM {
    my ($ts, $no_check) = @_;
    my $path = $prontus_varglb::DIR_SERVER . $prontus_varglb::CONFIG{$prontus_varglb::PRONTUS_ID}{'DIR_SITE'} . $prontus_varglb::DIR_ARTIC. '/' . substr($ts,0,8) . $prontus_varglb::DIR_MAM .'/'.$ts;

    return $path if ($no_check);

    if (!glib_fildir_03::check_dir($path)) {
        return '';
    }
    return $path;
}

# valida la hora completa hh:mm:ss
sub validaHoralarge {
	my ($hora) = @_;
	return 0 unless($hora =~ /^(\d\d):(\d\d):(\d\d)$/);
	my $hr = $1;
	my $min = $2;
	my $seg = $3;
	return 0 unless($hr >= 0 && $hr <= 23);
	return 0 unless($min >= 0 && $min <= 59);
	return 0 unless($seg >= 0 && $seg <= 59);
	return 1;
}

# valida la fecha en formato dd/mm/aaaa
sub validaFecha {
	my ($fecha) = @_;
	return 0 unless($fecha =~ /^(\d\d)\/(\d\d)\/(\d{4})$/);
	my $dia = $1;
	my $mes = $2;
	my $anio = $3;
	return 0 unless($dia >= 1 && $dia <= 31);
	return 0 unless($mes >= 1 && $mes <= 12);
	return 1;
}

1;
