package LATMOS::Accounts::Web::Model::AttrFormsA;

use strict;
use warnings;
use base 'LATMOS::Accounts::Bases::Attributes';
use base 'Catalyst::Model';
use LATMOS::Accounts::Log;
use Date::Parse;
use DateTime;
use DateTime::TimeZone;

=head1 NAME

LATMOS::Accounts::Web::Model::AttrForms - Catalyst Model

=head1 DESCRIPTION

Catalyst Model.

=cut

sub escape {
    my ($self, $text) = @_;
    $text ||= '';
    for ($text) {
        s/&/&amp;/g;
        s/</&lt;/g;
        s/>/&gt;/g;
        s/"/&quot;/g;
    }
    $text;
}

sub new {
    my ($class) = @_;
    bless({}, $class);
}

# call either OBJ or type + base

sub ACCEPT_CONTEXT {
    my ($self, $c, $attributes, $base_or_object, $maybe_otype) = @_;

    my $new = LATMOS::Accounts::Bases::Attributes->new($attributes, $base_or_object, $maybe_otype);
    $new->{c} = $c;
    $new->{htmlname} = $attributes;
    $new->{htmlname} =~ s/[\.-]/_/g;
    $new->{htmlid} = $attributes;
    $new->{htmlid} =~ s/[\.-]/_/g;
    $new->{valcount} = 0;
    $new->{hconfig} = LATMOS::Accounts::Web->config->{attrs}{$attributes} || {};
    bless($new, __PACKAGE__);
}

sub htmlname {
    $_[0]->{htmlname};
}

sub htmlid {
    my ($self) = @_;

    if ($self->{valcount}) {
        return sprintf('%s_%03d', $self->{htmlid}, $self->{valcount});
    } else {
        return $_[0]->{htmlid};
    }
}

sub htmlnewid {
    my ($self) = @_;

    $self->{valcount}++;

    return $self->htmlid;
}

sub hconfig {
    my ($self, $val) = @_;
    $self->{hconfig}{$val}
}

sub attr_label {
    my ($self, $label, $hint) = @_;
    $label ||= '';
    
    $hint = $self->hconfig('hint');

    return sprintf('<label %sfor="%s">%s</label>',
        ($hint ? sprintf('title="%s"', $self->escape($hint)) : ''),
        $self->escape($self->htmlname),
        $self->escape($self->label || $self->htmlname),
    );
}

sub attr_raw_value {
    my ($self) = @_;

    my @val = grep { $_ } (exists($self->{c}->req->params->{$self->htmlname}))
        ? ($self->{c}->req->param($self->htmlname))
        : $self->getValues;

    if (@val) {
        return @val;
    } elsif(!$self->object) {
        return (grep { $_ } ($self->default_value))
    }
}

sub attr_field_name {
    my ($self) = @_;

    $self->htmlname;
}

sub attr_field {
    my ($self, $type) = @_;

    # Force Array context:
    my @attr_raw_value = $self->attr_raw_value;
    if (!$self->multiple) {
        push(@attr_raw_value, undef) unless(@attr_raw_value);
    }
    my @htmls = ();

    foreach my $attr_raw_value (@attr_raw_value) {
        $self->htmlnewid;
        push(@htmls, $self->attr_item($attr_raw_value));
    }

    if (my $js = $self->attr_js) {
        push(@htmls,
            qq[ <script>
            \$( function() {
            $js
            });
            </script>]
        );
    }

    my $addempty = '';
    if ($self->{multiple} && !$self->readonly) {

        my $old = $self->{valcount} + 1;
        $self->{valcount} = 999;
        my $code = $self->attr_item('');
        $code =~ s/'/\\'/g;
        $code =~ s/\n/ /gm;

        $addempty = sprintf('<div id="%s_div"></div>', $self->htmlid);
        $addempty .= "\n";
        $addempty .= sprintf(q|
            <button id="%s_add" type="button" style="display:block">+</button>
            <script type="text/javascript">
            var cn_%s = %d;
            $( '#%s_add' ).click(function(even, ui) {
                $('#%s_div').append('%s'.replace(/%d/g, cn_%s)).append('<br>');

                cn_%s++;
                %s
            });
            </script>
            |,
            $self->htmlid,
            $self->htmlid,
            $old,
            $self->htmlid,
            $self->htmlid,
            $code,
            $self->{valcount},
            $self->htmlid,
            $self->htmlid,
            $self->attr_js,
        );

        $addempty .= "\n";

    }

    return join("<br>\n", @htmls) . $addempty;
}

sub attr_item {
    my ($self, $value) = @_;

    my $html = '';

    my $type = 'attr_' . uc($self->form_type);

    if ($self->can($type)) {
        $html .= $self->$type($value);
    } else {
        $html .= $self->attr_TEXT($value);
    }

    $html .= q|<span class="inputvalidate" id="|. $self->htmlid . q|_check"></span>|;

    if (my $ref = $self->reference) {
        my $uri_part = $self->_uri_part($ref);
        if ($self->base->attribute($ref, 'displayName')) {
            my $text = '';
            if ($value &&
                (my $obj = $self->base->get_object($ref, $value))) {
                $text = $obj->get_attributes('displayName');
            }
            #$html .= sprintf(
                #qq|<span id="${htmlid}_ref" style="margin-left: 1em">$text</span>|,
                #   $self->escape($text),
                #);
        } elsif($value && $uri_part) {
            $html .= sprintf(
                '<a href="%s"><img class="attr" src="%s" title="%s"></a>',
                $self->{c}->uri_for('/', $uri_part, $value),
                $self->{c}->uri_for('/static', 'images', 'arrow-right.png'),
                $value,
            );
        }
    }

    $html
}

sub attr_js {
    my ($self, $value) = @_;

    my $type = 'attr_' . uc($self->form_type) . '_js';

    if ($self->can($type)) {
        return $self->$type($value);
    } else {
        return '';
    }
}


sub attr_TEXT {
    my ($self, $value, $name, $id) = @_;

    return sprintf(
        '<input type="text" id="%s" name="%s" value="%s" size="%d">',
        $self->escape($id   || $self->htmlid),
        $self->escape($name || $self->htmlname),
        $self->escape($value),
        $self->form_option('length') || 30,
    );

}

sub attr_TEXT_js {
    my ($self) = @_;

    my $html = '';

    if ($self->uniq) {
        $html .= sprintf(q|
                $( '[name="%s"]' ).on('input', function() {
                    var id = $(this).attr('id');
                    $.ajax({
                        method: "POST",
                        url: '%s',
                        data: { val: $(this).val() },
                    }). done(function( msg ) {
                        $( '#' + id + '_check' ).html (msg);
                    });
                    return false;
                });
        |,
        $self->htmlname,
        $self->{c}->uri_for('/ajax', 'objattrexist', $self->otype, $self->name),
        );
    }

    $html;
}

sub attr_LABEL {
    my ($self, $value) = @_;

    if ($self->real_form_type =~ m/(DATE|DATETIME)/) {
        if (my $time = str2time($value)) {
            my $dt = DateTime->from_epoch(epoch => $time);
            $dt->set_time_zone( DateTime::TimeZone->new( name => 'local' ) );
            $value = $dt->dmy('/') . ($self->real_form_type eq 'DATE'
                ? ''
                : ' ' . $dt->hms(':'));
        }
    }

    return $self->escape($value);
}

sub attr_TEXTAREA {
    my ($self, $value) = @_;
    return sprintf(
        '<textarea id="%s" name="%s" cols="40">%s</textarea>',
        $self->escape($self->htmlid),
        $self->escape($self->htmlname),
        $self->escape($value || ''),
    );
}


sub attr_DATE {
    my ($self, $value, $name, $id) = @_;

    if (my $time = str2time($value)) {
        my $dt = DateTime->from_epoch(epoch => $time);
        $dt->set_time_zone( DateTime::TimeZone->new( name => 'local' ) );
        $value = $dt->dmy('/')
    }

    return sprintf(
        '<input type="text" id="%s" name="%s" value="%s" size="%d">',
        $self->escape($id   || $self->htmlid),
        $self->escape($name || $self->htmlname),
        $self->escape($value),
        $self->form_option('length') || 20,
    );
}

sub attr_DATE_js {
    my ($self, $value) = @_;
    return sprintf(q|
        $('[name="%s"]').datepicker( {
            changeMonth: true,
            changeYear: true,
            dateFormat: 'dd/mm/yy'
        } );
    |, $self->escape($self->htmlname));
}

sub attr_DATETIME {
    my ($self, $value, $name, $id) = @_;

    if (my $time = str2time($value)) {
        my $dt = DateTime->from_epoch(epoch => $time);
        $dt->set_time_zone( DateTime::TimeZone->new( name => 'local' ) );
        $value = $dt->dmy('/') . ' ' . $dt->hms(':')
    }

    return sprintf(
        '<input type="text" id="%s" name="%s" value="%s" size="%d">',
        $self->escape($id   || $self->htmlid),
        $self->escape($name || $self->htmlname),
        $self->escape($value),
        $self->form_option('length') || 20,
    );
}

sub attr_DATETIME_js {
    my ($self, $value) = @_;
    return sprintf(q|
        $('[name="%s"]').datepicker( {
            changeMonth: true,
            changeYear: true,
            dateFormat: 'dd/mm/yy'
        } );
    |, $self->escape($self->htmlname));
}

sub attr_CHECKBOX {
    my ($self, $value) = @_;
    $value ||= '';

    return sprintf('<input type="checkbox" id="%s" name="%s"%s>%s',
        $self->escape($self->htmlid),
        $self->escape($self->htmlname),
        ($value ? '  checked="yes"' : ''),
        ($self->form_option('rawvalue') ? " $value" : ''),
    );
}

sub attr_LIST {
    my ($self, $value) = @_;

    my @values = $self->can_values;
    $value ||= '';

    if (@values < 5) {
        return sprintf(q|<select id="%s" name="%s">%s%s</select>|,
            $self->htmlid,
            $self->htmlname,
            ($self->mandatory ? '' : '<option value="">--</option>'),
            join(",\n", map { $_ = sprintf('<option value="%s"%s>%s</option>', $_, ($_ eq $value ? ' selected="selected"' : ''), $self->display($_)) } sort $self->can_values),
        );
    } else {
        my $html = $self->attr_TEXT($self->display($value));
    }
}

sub attr_LIST_js {
    my ($self) = @_;
    return sprintf(q|
            $('[name="%s"]').autocomplete({
                delay: 200,
                minLength: 0,
                source: '%s',
            })
            .autocomplete( "instance" )._renderItem = function( ul, item ) {
                return $( "<li>" )
                .append( "<a>" + item.label + " (" + item.value +  ")</a>" )
                .appendTo( ul );
            };
        |,
        $self->htmlname,
        $self->{c}->uri_for('/json/refval', $self->otype, $self->name),
    );
}

sub _uri_part {
    my ($self, $ref) = @_;
    my $uri_part = {
        user => 'users',
        group => 'groups',
        nethost => 'nethosts',
        netzone => 'netzones',
        site => 'sites',
        aliasess => 'aliases',
    }->{$ref};
}

sub _attr_js_item {
    my ($self, $value, $htmlid) = @_;

    $htmlid = $self->htmlid;
    my (@js);

    if (my $ref = $self->reference) {
        my $uri_part = $self->_uri_part($ref);
        if ($self->base->attribute($ref, 'displayName')) {
            push(@js, 
                $self->{c}->prototype->observe_field( $htmlid,
                    {
                        update => "${htmlid}_ref",
                        url => $self->{c}->uri_for('/ajax', 'rawattr', $ref),
                        frequency => 1,
                        with   => "'attr=displayName&id=' + element.options[element.selectedIndex].text",
                    }
                )
            ) if ($self->form_type =~ /list/i);
        }
    }

    return(join("\n", @js));
}


=head1 AUTHOR

Thauvin Olivier

=head1 LICENSE

This library is free software, you can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

1;
