#!/usr/bin/perl

#
# Copyright (C) 2019 Nethesis S.r.l.
# http://www.nethesis.it - nethserver@nethesis.it
#
# This script is part of NethServer.
#
# NethServer is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License,
# or any later version.
#
# NethServer is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with NethServer.  If not, see COPYING.
#

use strict;
use esmith::ConfigDB;
use esmith::event;
use JSON;

require '/usr/libexec/nethserver/api/lib/helper_functions.pl';

my $eventName = undef;
my $ret;
my $jitsiUrlChanged = 0;

my $db = esmith::ConfigDB->open();

my $input = readInput();
my %props = ();

   %props = (
      'DefaultLocale' => $input->{'configuration'}->{'DefaultLocale'},
      'DefaultTimezone' => $input->{'configuration'}->{'DefaultTimezone'},
      'DefaultToolbarIconsSize' => $input->{'configuration'}->{'DefaultToolbarIconsSize'},
      'PublicUrl' => $input->{'configuration'}->{'PublicUrl'},
      'DavServerUrl' => $input->{'configuration'}->{'DavServerUrl'},
      'PbxProvider' => $input->{'configuration'}->{'PbxProvider'},
      'PbxProviderNethvoiceWebrestUrl' => $input->{'configuration'}->{'PbxProviderNethvoiceWebrestUrl'},
      'MinMemory' => $input->{'configuration'}->{'MinMemory'},
      'MaxMemory' => $input->{'configuration'}->{'MaxMemory'},
      'VirtualHost' => $input->{'configuration'}->{'VirtualHost'},
  );

# Check if JitsiUrl has changed
if ($db->get_prop('conference', 'JitsiUrl') ne $input->{'configuration'}->{'JitsiUrl'}) {
    $jitsiUrlChanged = 1;
}

if($input->{'action'} eq 'edit') {
    $db->get('webtop')->merge_props(%props);

    if ($jitsiUrlChanged) {
        $db->get('conference')->set_prop('JitsiUrl', $input->{'configuration'}->{'JitsiUrl'});
    }
} else {
    error();
}

esmith::event::set_json_log(1);

if (not esmith::event::event_signal('nethserver-webtop5-update')) {
    $ret = {
        'type' => 'Error',
        'message' => 'webtop5.api_update_failed',
        'attributes' => {
            'event_name' => 'nethserver-webtop5-update'
        }
    };
    print encode_json($ret);
    exit(1);
}

if ($jitsiUrlChanged) {
    # trigger event nethserver-conference-save
    if (not esmith::event::event_signal('nethserver-conference-save')) {
        $ret = {
            'type' => 'Error',
            'message' => 'webtop5.api_update_failed',
            'attributes' => {
                'event_name' => 'nethserver-conference-save'
            }
        };
        print encode_json($ret);
        exit(1);
    }
}

print encode_json({'state' => 'success'});
exit(0);
