package LATMOS::Accounts::Web::Model::AttrForms;

use strict;
use warnings;
use base 'Catalyst::Model';

=head1 NAME

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

=head1 DESCRIPTION

Catalyst Model.

=cut

my $attrs = {
    uid => [ 'Login' ],
    uidNumber => [ 'UID' ],
    gidNumber => [ 'GID', 'select:group:gidNumber' ],
    manager => [ 'Responsable', 'select-N:user:uid' ],
    managedBy => [ 'Responsable', 'select-N:user:uid' ],
    sn => [ 'Nom' ],
    givenName => [ 'Prénom' ],
    homeDirectory => [ 'Home' ],
    loginShell => [ 'Shell' ],
    physicalDeliveryOfficeName => [ 'Bureau' ],
    telephoneNumber => [ 'Téléphone' ],
    otherTelephone => [ 'Téléphone (autre)' ],
    company => [ 'Société' ],
    l => [ 'Ville' ],
    postalCode => [ 'Code postal' ],
    postOfficeBox => [ 'BP' ],
    department => [ 'Département', 'select-N:department' ],
    streetAddress => [ 'Rue', 'textarea' ],
    st => [ 'Etat' ],
    title => [ 'Fonction' ],
    expire => [ 'Expire le', 'date' ],
    st => [ 'État (US)' ],
    sutype => [ 'Structure admin.', 'select-N:sutype' ],
    exported => [ undef, 'checkbox' ],
};

my $forms = {
    user => {
        name => 'Système',
        acl => 'admin',
        attrs => [ qw(
            sn givenName description
            uid uidNumber gidNumber gecos homeDirectory loginShell
            mail
        ) ],
    },
    useraddress => {
        name => 'Adresse',
        attrs => [ qw(
            initials
            telephoneNumber
            otherTelephone
            mail
            streetAddress
            postOfficeBox
            postalCode
            l
            st
            physicalDeliveryOfficeName
        ) ],
    },
    userstatus => {
        name => 'Status',
        attrs => [ qw(
            company
            manager
            department
            title
            expire
            exported
        ) ],
    },
    site => {
        name => 'Site',
        attrs => [ qw(
            description
            streetAddress
            postOfficeBox
            postalCode
            st
            l
        ) ],
    },
    department => {
        name => 'Département',
        attrs => [qw(description manager) ],
    },
    group => {
        name => 'Système',
        acl => 'admin',
        attrs => [ qw(
            gidNumber description
            managedBy
            sutype exported
        ) ],
    },
};

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, $form, $object, $base) = @_;
    my $new = {};
    $new->{c} = $c;
    $new->{form} = $form;
    $new->{object} = $object if (ref $object);
    $new->{base} = $base || ($object ? $object->base : undef) or return $self;
    $new->{otype} = ref $object ? $object->type : $object;
    bless($new, 'LATMOS::Accounts::Web::Model::AttrForms');
}

sub base {
    my ( $self ) = @_;
    $self->{base}
}

sub otype {
    my ($self) = @_;
    $self->{otype};
}

sub label {
    my ($self) = @_;
    $forms->{$self->{form}}->{name} || ''
}

sub attributes {
    my ($self) = @_;
    grep { $self->base->get_field_name($self->otype, $_, 'a') }
    @{ $forms->{$self->{form}}->{attrs} };
}

sub attr_label {
    my ($self, $attr) = @_;
    return $self->escape($attrs->{$attr}[0] || $attr);
}

sub attr_raw_value {
    my ($self, $attr) = @_;
    return $self->{c}->req->param($attr) ||
        ($self->{object} ? $self->{object}->get_c_field($attr) : '')
}

sub attr_field {
    my ($self, $attr, $type) = @_;
    $type ||= $self->base->get_field_name($self->otype, $attr, 'w')
        ? $attrs->{$attr}[1] || ''
        : 'label';
    # exception: gidNumber is used also in group, but we don't want
    # group list here, really the number !
    $type = '' if (($self->{form} || '') =~ /^group/ && $attr eq 'gidNumber');
    for ($type) {
        /^textarea$/ and return sprintf(
            '<textarea name="%s">%s</textarea>',
            $self->escape($attr),
            $self->escape($self->attr_raw_value($attr)),
        );
        /^label$/ and return $self->escape(
            $self->attr_raw_value($attr)
        );
        /^date$/ and do {
            my ($date, $time) = split(/ /, $self->attr_raw_value($attr) || '');
            if ($date && $date =~ /^(\d+)-(\d+)-(\d+)$/) {
                $date = "$3/$2/$1";
            }
            my $html = "\n" . q{<SCRIPT LANGUAGE="JavaScript" ID="js13">
            var cal13 = new CalendarPopup();
            </SCRIPT>} . "\n";
            $html .= sprintf(
                '<input type="text" name="%s" value="%s">',
                $attr,
                $self->escape($date)
            );
            $html .= q{<DIV ID="testdiv1" STYLE="position:absolute;visibility:hidden;background-color:white;layer-background-color:white;"></DIV>};
            $html .= qq{
            <A HREF="#"
                onClick="cal13.select(document.forms[0].$attr,'anchor13','dd/MM/yyyy');return false;"
                TITLE="cal13.select(document.forms[0].$attr,'anchor13','dd/MM/yyyy'); return false;"
                NAME="anchor13" ID="anchor13">
                <img src="} . $self->{c}->uri_for(qw(/static icons view-calendar-day.png))
                . qq{" style="ref"></A>} . "\n";
            return $html;
        };
        /^checkbox$/ and do {
            return sprintf('<input type="checkbox" name="%s"%s>',
                $attr,
                $self->attr_raw_value($attr) ? '  checked="yes"' : ''
            );
        };
        /^select(-\w+)?:([^:]+)(?::(.*))?$/ and do {
            my $options = $1 || '';
            my $otype = $2;
            my $keyfield = $3;
            my $select = sprintf('<select name="%s">',
                $self->escape($attr)) . "\n";
            $select .= '<option value="">--</option>' . "\n" if ($options =~ /N/);
            my $value = $self->attr_raw_value($attr) || '';
            foreach my $id ($self->base->list_objects($otype)) {
                my $obj = $self->base->get_object($otype, $id) or next;
                my $val = $keyfield ? $obj->get_c_field($keyfield) : $id;
                $select .= sprintf(
                    '    <option value="%s"%s>%s</options>',
                    $self->escape($val),
                    $value eq $val ? ' "selected"' : '',
                    $self->escape($id),
                );
                $select .= "\n";
            }
            $select .= "</select>\n";
            return $select;
        };
    }
    return sprintf(
        '<input type="text" name="%s" value="%s">',
        $attr,
        $self->escape($self->attr_raw_value($attr))
    );
}

sub submit {
    my ($self) = @_;
    return sprintf(
        '<input type="submit" name="%s">',
        $self->escape($self->label),
    );
}

sub set_attrs {
    my ($self) = @_;
    $self->{c}->req->param($self->label) or return;
    $self->{object}->set_c_fields(
        map {
            $_ =>
                ($attrs->{$_}[1] || '') eq 'checkbox'
                ? ($self->{c}->req->param($_) ? 1 : 0)
                : $self->{c}->req->param($_)
        } $self->attributes
    ) or return;
    $self->{object}->base->commit;
    $self->{c}->model('Accounts')->sync->sync_object($self->{object}->type, $self->{object}->id);
}

=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;
